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, useGetFinancialInfo, useGetProvines } from '../hooks/useFinancialData'
import Select from '../../../components/Select'
import PageLoading from '../../../components/PageLoading'
import { toast } from 'react-toastify'
import { ErrorType } from '../../../helpers/types'

const Legal: FC = () => {

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

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

    useEffect(() => {

        if (getFinancialInfo.data?.data?.user?.legalUser) {
            setIsReadOnly(true)
            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])


    return (
        <div className='bg-white rounded-3xl xl:p-6 p-4 mt-8 text-sm'>
            {
                getProvines.isPending || getFinancialInfo.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('companyRegisteredName')}
                                        error_text={formik.touched.companyRegisteredName && formik.errors.companyRegisteredName ? formik.errors.companyRegisteredName : ''}
                                        readOnly={isReadOnly}
                                    />
                                </div>

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

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

                                {
                                    !isReadOnly &&
                                    <div className='mt-8 flex justify-end'>
                                        <Button
                                            className='w-fit 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