import { useFormik } from 'formik'
import { FC, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import Input from '../../../components/Input'
import Select from '../../../components/Select'
import Textarea from '../../../components/Textarea'
import Button from '../../../components/Button'
import { InfoCircle, TickCircle } from 'iconsax-react'
import { CreateRealUserType, ProvinesItemType } from '../types/FinancialTypes'
import * as Yup from 'yup'
import { useCreateRealUser, useGetCities, useGetProvines, useGetRealInfo } from '../hooks/useFinancialData'
import { toast } from '../../../components/Toast'
import { ErrorType } from '../../../helpers/types'
import DatePickerComponent from '../../../components/DatePicker'
import { useGetProfile } from '../../profile/hooks/useProfileData'

const Personal: FC = () => {

    const { t } = useTranslation('global')

    const [isReadOnly, setIsReadOnly] = useState<boolean>(false)
    const [provinesId, setProvinesId] = useState<string>('')
    const createRealUser = useCreateRealUser()
    const getProvines = useGetProvines()
    const getRealInfo = useGetRealInfo()
    const getCities = useGetCities(provinesId)
    const getProfile = useGetProfile()

    const formik = useFormik<CreateRealUserType>({
        initialValues: {
            address: '',
            cityId: '',
            fatherName: '',
            birthDate: '',
            firstName: '',
            gender: '',
            lastName: '',
            nationalCode: '',
            nationality: '',
            phone: '',
            postalCode: ''
        },
        validationSchema: Yup.object({
            address: Yup.string().required(t('errors.required')),
            cityId: Yup.string().required(t('errors.required')),
            fatherName: Yup.string().required(t('rerrors.equired')),
            gender: Yup.string().required(t('errors.required')),
            firstName: Yup.string().required(t('errors.required')),
            lastName: Yup.string().required(t('rerrors.equired')),
            nationalCode: Yup.string().required(t('errors.required')),
            nationality: Yup.string().required(t('errors.required')),
            phone: Yup.string().required(t('errors.required')),
            postalCode: Yup.string().required(t('errors.required')),
            birthDate: Yup.string().required(t('errors.required'))
        }),
        onSubmit: values => {
            const params = {
                ...values,
                cityId: +values.cityId
            }
            createRealUser.mutate(params, {
                onSuccess: () => {
                    toast(t('success'), 'success')
                    window.location.reload()
                },
                onError(error: ErrorType) {
                    toast(error.response?.data?.error.message[0], 'error')
                },
            })
        }
    })

    useEffect(() => {

        if (getRealInfo.data?.data?.realUser) {
            const data = getRealInfo.data?.data?.realUser
            setIsReadOnly(true)
            formik.setValues({
                address: data.address.fullAddress,
                cityId: data.address?.city?.id,
                fatherName: data?.fatherName,
                gender: data?.gender,
                nationality: data?.nationality,
                postalCode: data?.address?.postalCode,
                birthDate: data?.birthDate,
                firstName: data?.firstName,
                lastName: data?.lastName,
                nationalCode: data?.nationalCode,
                phone: data?.phone
            })
            setProvinesId(data?.address?.city?.province?.id)
        }

    }, [getRealInfo.data])

    useEffect(() => {

        if (getProfile.data && getProfile.data?.data?.user?.financialType) {
            setIsReadOnly(true)
        }

    }, [getProfile.data])



    return (
        <div className='bg-white rounded-3xl xl:p-6 p-4 mt-8 text-sm'>
            <div className='mt-8 flex xl:flex-row flex-col xl:gap-0 gap-7 border-b pb-7'>
                <div className='flex-1'>
                    <div>
                        {t('financial.personal_information')}
                    </div>
                    <div className='text-description text-xs mt-2'>
                        {t('financial.enter_your_personal_information')}
                    </div>
                </div>
                <div className='flex-1'>
                    <div className='flex  xl:gap-6 gap-3'>
                        <Input
                            label={t('financial.name')}
                            {...formik.getFieldProps('firstName')}
                            error_text={formik.touched.firstName && formik.errors.firstName ? formik.errors.firstName : ''}
                            readOnly={isReadOnly}
                        />

                        <Input
                            label={t('financial.family')}
                            {...formik.getFieldProps('lastName')}
                            error_text={formik.touched.lastName && formik.errors.lastName ? formik.errors.lastName : ''}
                            readOnly={isReadOnly}
                        />
                    </div>
                    <div className='flex  xl:gap-6 gap-3 mt-8'>
                        <Select
                            label={t('financial.sex')}
                            placeholder={t('select')}
                            items={[
                                {
                                    label: t('man'),
                                    value: 'MALE'
                                },
                                {
                                    label: t('woman'),
                                    value: 'FEMALE'
                                },
                            ]}
                            {...formik.getFieldProps('gender')}
                            error_text={formik.touched.gender && formik.errors.gender ? formik.errors.gender : ''}
                            readOnly={isReadOnly}
                        />

                        <Input
                            label={t('financial.father_name')}
                            {...formik.getFieldProps('fatherName')}
                            error_text={formik.touched.fatherName && formik.errors.fatherName ? formik.errors.fatherName : ''}
                            readOnly={isReadOnly}
                        />
                    </div>

                    <div className='flex  xl:gap-6 gap-3 mt-8'>
                        <Input
                            label={t('financial.phone_number')}
                            {...formik.getFieldProps('phone')}
                            error_text={formik.touched.phone && formik.errors.phone ? formik.errors.phone : ''}
                            readOnly={isReadOnly}
                        />

                        <Input
                            label={t('financial.national_code')}
                            {...formik.getFieldProps('nationalCode')}
                            error_text={formik.touched.nationalCode && formik.errors.nationalCode ? formik.errors.nationalCode : ''}
                            readOnly={isReadOnly}
                        />
                    </div>

                    <div className='flex  xl:gap-6 gap-3 mt-8'>
                        <DatePickerComponent
                            label={t('financial.date_of_birth')}
                            onChange={(value) => formik.setFieldValue('birthDate', value)}
                            placeholder={t('financial.date_of_birth')}
                            error_text={formik.touched.birthDate && formik.errors.birthDate ? formik.errors.birthDate : ''}
                            readOnly={isReadOnly}
                            defaulValue={formik.values.birthDate}
                        />

                        <Select
                            items={[
                                {
                                    label: t('financial.iranian'),
                                    value: 'IRANIAN'
                                },
                                {
                                    label: t('financial.foreign'),
                                    value: 'FOREIGN'
                                },
                            ]}
                            {...formik.getFieldProps('nationality')}
                            error_text={formik.touched.nationality && formik.errors.nationality ? formik.errors.nationality : ''}
                            readOnly={isReadOnly}
                            label={t('financial.nationality')}
                        />
                    </div>

                    {/* <div className='flex  xl:gap-6 gap-3 mt-8'>
                        <Input
                            label={t('financial.company_phone')}
                            {...formik.getFieldProps('number')}
                            error_text={formik.touched.number && formik.errors.number ? formik.errors.number : ''}
                            readOnly={isReadOnly}
                        />

                        <Input
                            label={t('financial.company_postal_code')}
                            {...formik.getFieldProps('postalCode')}
                            error_text={formik.touched.postalCode && formik.errors.postalCode ? formik.errors.postalCode : ''}
                            readOnly={isReadOnly}
                        />
                    </div> */}

                </div>
            </div>

            <div className='mt-8 flex xl:flex-row flex-col xl:gap-0 gap-7  pb-7'>
                <div className='flex-1'>
                    <div>
                        {t('financial.address')}
                    </div>
                    <div className='text-description text-xs mt-2'>
                        {t('financial.enter_address')}
                    </div>
                </div>
                <div className='flex-1'>
                    <div className='flex  xl:gap-6 gap-3'>
                        <Select
                            value={provinesId}
                            label={t('financial.state')}
                            placeholder={t('select')}
                            items={getProvines.data?.data?.provinces.map((item: ProvinesItemType) => ({ label: item.name, value: item.id }))}
                            onChange={(e) => setProvinesId(e.target.value)}
                            readOnly={isReadOnly}
                        />
                        <Select
                            label={t('financial.city')}
                            placeholder={t('select')}
                            items={getCities.data?.data?.cities ? getCities.data?.data?.cities.map((item: ProvinesItemType) => ({ label: item.name, value: item.id })) : []}
                            {...formik.getFieldProps('cityId')}
                            error_text={formik.touched.cityId && formik.errors.cityId ? formik.errors.cityId : ''}
                            readOnly={isReadOnly}
                        />
                    </div>

                    <div className='mt-8'>
                        <Input
                            label={t('financial.company_postal_code')}
                            {...formik.getFieldProps('postalCode')}
                            error_text={formik.touched.postalCode && formik.errors.postalCode ? formik.errors.postalCode : ''}
                            readOnly={isReadOnly}
                        />
                    </div>

                    <div className='flex  xl:gap-6 gap-3 mt-8'>
                        <Textarea
                            {...formik.getFieldProps('address')}
                            error_text={formik.touched.address && formik.errors.address ? formik.errors.address : ''}
                            label={t('financial.address')}
                            readOnly={isReadOnly}
                        />
                    </div>

                    <div className='mt-8 h-10 text-xs bg-[#FFF2F2] text-[#DB0105] rounded-xl px-4 flex gap-2 items-center'>
                        <InfoCircle
                            size={18}
                            color='#DB0105'
                        />
                        <div>{t('financial.notice_cannot_edit')}</div>
                    </div>

                    <div className='mt-8 flex justify-end'>
                        <Button
                            className='xl:w-fit px-7'
                            onClick={() => formik.handleSubmit()}
                            isLoading={createRealUser.isPending}
                            disabled={isReadOnly}
                        >
                            <div className='flex gap-2 items-center'>
                                <TickCircle
                                    size={24}
                                    color='white'
                                />
                                <div>{t('save')}</div>
                            </div>
                        </Button>
                    </div>
                </div>
            </div>
        </div>
    )
}

export default Personal