import { mdiAccount, mdiBriefcase, mdiHumanMaleFemale, mdiHeart } from '@mdi/js'
import Head from 'next/head'
import React, { ReactElement, useEffect, useState } from 'react'
import "react-datepicker/dist/react-datepicker.css";

import CardBox from '../../components/CardBox'
import LayoutAuthenticated from '../../layouts/Authenticated'
import SectionMain from '../../components/SectionMain'
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton'
import { getPageTitle } from '../../config'

import { Field, Form, Formik } from 'formik'
import FormField from '../../components/FormField'
import BaseDivider from '../../components/BaseDivider'
import BaseButtons from '../../components/BaseButtons'
import BaseButton from '../../components/BaseButton'
import { SelectField } from "../../components/SelectField";
import {RichTextField} from "../../components/RichTextField";

import { update, fetch } from '../../stores/profiles/profilesSlice'
import { useAppDispatch, useAppSelector } from '../../stores/hooks'
import { useRouter } from 'next/router'

const EditProfilesPage = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  
  const initVals = {
    name: '',
    description: '',
    persona_data: {
      age: '',
      gender: '',
      occupation: '',
      interests: '',
      language: ''
    }
  }
  
  const [initialValues, setInitialValues] = useState(initVals)
  const { profiles } = useAppSelector((state) => state.profiles)
  const { id } = router.query

  useEffect(() => {
    if (id) {
      dispatch(fetch({ id: id }))
    }
  }, [id, dispatch])

  useEffect(() => {
    if (profiles && typeof profiles === 'object') {
      const mergedValues = {
        ...initVals,
        ...profiles,
        persona_data: {
          ...initVals.persona_data,
          ...(profiles.persona_data || {})
        }
      }
      setInitialValues(mergedValues)
    }
  }, [profiles])

  const handleSubmit = async (data) => {
    await dispatch(update({ id: id, data }))
    await router.push('/profiles/profiles-list')
  }

  return (
    <>
      <Head>
        <title>{getPageTitle('Edit Persona Profile')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiAccount} title={'Edit Persona Profile'} main>
        {''}
        </SectionTitleLineWithButton>
        <CardBox>
          <Formik
            enableReinitialize
            initialValues={initialValues}
            onSubmit={(values) => handleSubmit(values)}
          >
            <Form>
              <FormField label="Persona Name">
                  <Field name="name" placeholder="e.g. John Doe" />
              </FormField>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <FormField label="Age">
                    <Field name="persona_data.age" type="number" placeholder="Age" />
                </FormField>

                <FormField label="Gender">
                    <Field name="persona_data.gender" component={SelectField} options={[
                      { label: 'Male', value: 'male' },
                      { label: 'Female', value: 'female' },
                      { label: 'Non-binary', value: 'non-binary' },
                      { label: 'Other', value: 'other' }
                    ]} />
                </FormField>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <FormField label="Occupation">
                    <Field name="persona_data.occupation" placeholder="e.g. Software Engineer" />
                </FormField>

                <FormField label="Language Preference">
                    <Field name="persona_data.language" placeholder="e.g. Arabic, English" />
                </FormField>
              </div>

              <FormField label="Interests & Hobbies">
                  <Field name="persona_data.interests" placeholder="e.g. Photography, Travel, AI" />
              </FormField>

              <FormField label='Bio / Additional Context' hasTextareaHeight>
                  <Field
                      name='description'
                      id='description'
                      component={RichTextField}
                  ></Field>
              </FormField>

              <BaseDivider />
              <BaseButtons>
                <BaseButton type="submit" color="info" label="Update Persona" />
                <BaseButton type='reset' color='danger' outline label='Cancel' onClick={() => router.push('/profiles/profiles-list')}/>
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  )
}

EditProfilesPage.getLayout = function getLayout(page: ReactElement) {
  return (
      <LayoutAuthenticated permission={'UPDATE_PROFILES'}>
          {page}
      </LayoutAuthenticated>
  )
}

export default EditProfilesPage