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

const Legal: FC = () => {

    const { t } = useTranslation('global')
    const [isReadOnly, setIsReadOnly] = useState<boolean>(false)
    const [provinesId, setProvinesId] = useState<string>('')
    const getProvines = useGetProvines()
    const getLegalInfo = useGetLegalInfo()
    const getCities = useGetCities(provinesId)
    const createLegalUser = useCreateLegalUser()
    const getProfile = useGetProfile()

    const formik = useFormik<CreateLegalUserType>({
        initialValues: {
            address: '',
            cityId: '',
            registrationName: '',
            economicCode: '',
            nationalIdentity: '',
            phone: '',
            postalCode: '',
            registrationCode: ''
        },
        validationSchema: Yup.object({
            address: Yup.string().required(t('errors.required')),
            cityId: Yup.string().required(t('errors.required')),
            registrationName: Yup.string().required(t('errors.required')),
            economicCode: Yup.string().required(t('errors.required')),
            nationalIdentity: Yup.string().required(t('errors.required')),
            phone: Yup.string().required(t('errors.required')),
            postalCode: Yup.string().required(t('errors.required')),
            registrationCode: Yup.string().required(t('errors.required'))
        }),
        onSubmit: values => {
            const params = {
                ...values,
                cityId: +values.cityId
            }
            createLegalUser.mutate(params, {
                onSuccess: () => {
                    toast(t('success'), 'success')
                    window.location.reload()
                },
                onError(error: ErrorType) {
                    toast(error.response?.data?.error.message[0], 'error')
                },
            })
        }
    })

    // useEffect(() => {

    //     if (getFinancialInfo.data?.data?.user?.legalUser || getFinancialInfo.data?.data?.user?.realUser) {
    //         setIsReadOnly(true)
    //     }
    //     if (getFinancialInfo.data?.data?.user?.legalUser) {
    //         const data = getFinancialInfo.data.data?.user
    //         formik.setValues({
    //             address: data?.address.address,
    //             cityId: data?.address?.city?.id,
    //             companyRegisteredName: data?.legalUser.companyRegisteredName,
    //             economicCode: data?.legalUser.economicCode,
    //             nationalId: data?.legalUser.nationalId,
    //             number: data?.legalUser.number,
    //             postalCode: data?.address.postalCode,
    //             registrationId: data?.legalUser.registrationId
    //         })
    //         setProvinesId(data?.address?.city?.province?.id)
    //     }

    // }, [getFinancialInfo.data])

    useEffect(() => {

        if (getLegalInfo.data?.data?.legalUser) {
            setIsReadOnly(true)
        }
        if (getLegalInfo.data?.data?.legalUser) {
            const data = getLegalInfo.data?.data?.legalUser
            formik.setValues({
                address: data?.address.fullAddress,
                cityId: data?.address?.city?.id,
                registrationName: data.registrationName,
                economicCode: data.economicCode,
                nationalIdentity: data.nationalIdentity,
                phone: data.phone,
                postalCode: data?.address.postalCode,
                registrationCode: data.registrationCode
            })
            setProvinesId(data?.address?.city?.province?.id)
        }

    }, [getLegalInfo.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'>
            {
                getProvines.isPending || getLegalInfo.isPending ?
                    <PageLoading />
                    :
                    <Fragment>
                        <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.info_company')}
                                </div>
                                <div className='text-description text-xs mt-2'>
                                    {t('financial.enter_info_your_company')}
                                </div>
                            </div>
                            <div className='flex-1'>
                                <div className='flex items-end xl:gap-6 gap-3'>
                                    <Input
                                        label={t('financial.company_name')}
                                        {...formik.getFieldProps('registrationName')}
                                        error_text={formik.touched.registrationName && formik.errors.registrationName ? formik.errors.registrationName : ''}
                                        readOnly={isReadOnly}
                                    />
                                </div>

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

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

                                    <Input
                                        label={t('financial.economic_code')}
                                        {...formik.getFieldProps('economicCode')}
                                        error_text={formik.touched.economicCode && formik.errors.economicCode ? formik.errors.economicCode : ''}
                                        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.company_contact_info')}
                                </div>
                                <div className='text-description text-xs mt-2'>
                                    {t('financial.company_contact_address')}
                                </div>
                            </div>
                            <div className='flex-1'>

                                <div className='flex items-end 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='flex items-end xl:gap-6 gap-3 mt-8'>
                                    <Input
                                        label={t('financial.company_phone')}
                                        {...formik.getFieldProps('phone')}
                                        error_text={formik.touched.phone && formik.errors.phone ? formik.errors.phone : ''}
                                        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 className='flex items-end 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_legal')}</div>
                                </div>


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


                            </div>
                        </div>
                    </Fragment>
            }
        </div>
    )
}

export default Legal