import { FC, useCallback, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import AvatarImage from '../../assets/images/avatar_image.png'
import Button from '../../components/Button'
import { DocumentUpload } from 'iconsax-react'
import Input from '../../components/Input'
import DatePickerComponent from '../../components/DatePicker'
import { useGetProfile, useUpdateProfile } from './hooks/useProfileData'
import Username from './components/Username'
import { useDropzone } from 'react-dropzone'
import { toast } from '../../components/Toast'
import { useSingleUpload } from '../ticket/hooks/useTicketData'
import { ErrorType } from '../../helpers/types'
import { UpdateProfileType } from './types/ProfileTypes'
import PageLoading from '../../components/PageLoading'
import { useGetProvines } from '../financial/hooks/useFinancialData'
import { useFormik } from 'formik'
import * as Yup from 'yup'
import Email from './components/Email'
import Phone from './components/Phone'

const Profile: FC = () => {

    const { t } = useTranslation('global')
    const [file, setFile] = useState<File>()
    const getProvines = useGetProvines()
    const getProfile = useGetProfile()
    const [percent, setPercent] = useState<number>(0)
    const singleUpload = useSingleUpload(setPercent)
    const updateProfile = useUpdateProfile()

    const formik = useFormik<UpdateProfileType>({
        initialValues: {
            cityId: '',
            userAddress: '',
            postalCode: '',
        },
        validationSchema: Yup.object({
            cityId: Yup.string().required(t('errors.required')),
            userAddress: Yup.string().required(t('errors.required')),
            postalCode: Yup.string().required(t('errors.required')),
        }),
        onSubmit: (values) => {
            updateProfile.mutate(values, {
                onSuccess: () => {
                    toast(t('success'), 'success')
                },
                onError: (error: ErrorType) => {
                    toast(error.response?.data?.error?.message[0], 'error')
                }
            })
        }
    })

    useEffect(() => {

        if (getProfile.data) {
            formik.setValues({
                cityId: getProfile.data.data.user.city?.id || '',
                userAddress: getProfile.data.data.user.userAddress || '',
                postalCode: getProfile.data.data.user.postalCode || '',
            })
            if (getProfile.data.data.user.city) {
            }
        }

    }, [getProfile.data])


    const onDrop = useCallback((acceptedFiles: File[]) => {

        if (acceptedFiles.length > 0) {
            const file = acceptedFiles[0];
            if (file.type.startsWith('image/')) {
                setFile(file);
                const formData = new FormData()
                formData.append('file', file)
                singleUpload.mutate(formData, {
                    onSuccess: (data) => {
                        const params: UpdateProfileType = {
                            profilePic: data.data?.url
                        }
                        updateProfile.mutate(params, {
                            onSuccess: () => {
                                toast(t('profile.image_uploaded_successfully'), 'success')
                            },
                            onError: (error: ErrorType) => {
                                toast(error.response?.data?.error?.message[0], 'error')
                            }
                        })
                    },
                    onError: (error: ErrorType) => {
                        toast(error.response?.data?.error?.message[0], 'error')
                    }
                })
            } else {
                toast(t('errors.is_not_image'), 'error')
            }
        }

    }, [])
    const { getRootProps, getInputProps } = useDropzone({ onDrop })

    return (
        <div className='mt-4 '>
            <div>
                {t('profile.account_user')}
            </div>

            {
                getProfile.isPending || getProvines.isPending ?
                    <PageLoading />
                    :
                    <div className='bg-white rounded-3xl xl:p-6 p-4 mt-8 text-sm'>
                        <div className='xl:mt-10 mt-4 flex xl:flex-row flex-col xl:gap-0 gap-7 xl:items-center border-b pb-7'>
                            <div className='flex-1'>
                                <div>
                                    {t('profile.image_profile')}
                                </div>
                                <div className='text-description text-xs mt-2'>
                                    {t('profile.image_profile_desc')}
                                </div>
                            </div>
                            <div className='flex-1 flex xl:gap-6 gap-4'>
                                <img src={file ? URL.createObjectURL(file) : getProfile.data?.data?.user?.profilePic ? getProfile.data?.data?.user?.profilePic : AvatarImage} className='xl:size-20 size-14 rounded-full object-cover' />
                                <div>
                                    <Button
                                        isLoading={singleUpload.isPending || updateProfile.isPending}
                                        className='xl:w-[160px] w-fit px-4 xl:;px-0 h-8 xl:h-10 text-xs xl:text-sm'
                                        percentage={percent}
                                    >
                                        <input {...getInputProps()} />
                                        <div {...getRootProps()} className='flex items-center gap-3'>
                                            <DocumentUpload color='white' size={18} />
                                            <div>{t('profile.upload_image')}</div>
                                        </div>
                                    </Button>
                                    <p className='mt-3 items-center flex gap-0.5 text-description'>
                                        {t('profile.formats')}
                                        <div className='-mt-0.5'>{t('profile.format_image')}</div>
                                        <span>{t('profile.max_size')}</span>
                                    </p>
                                </div>
                            </div>
                        </div>

                        <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('profile.info_account')}
                                </div>
                                <div className='text-description text-xs mt-2'>
                                    {t('profile.auth_after_change_info')}
                                </div>
                            </div>
                            <div className='flex-1 '>
                                <Username
                                    username={getProfile.data?.data?.user?.userName}
                                />
                                <Email
                                    email={getProfile.data?.data?.user?.email}
                                    isVerified={getProfile.data?.data?.user?.emailVerified}
                                />
                                <Phone
                                    phone={getProfile.data?.data?.user?.phone}
                                />
                            </div>
                        </div>

                        <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('profile.personal_information')}
                                </div>
                                <div className='text-description text-xs mt-2'>
                                    {t('profile.enter_carefully_your_information')}
                                </div>
                            </div>
                            <div className='flex-1'>
                                <DatePickerComponent
                                    label={t('profile.date_of_birth')}
                                    onChange={() => { }}
                                    placeholder=''
                                    defaulValue={getProfile.data?.data?.user?.birthDate}
                                />

                                <div className='xl:mt-7 mt-4'>
                                    <Input
                                        label={t('profile.national_code')}
                                        value={getProfile.data?.data?.user?.nationalCode}
                                    />
                                </div>
                            </div>
                        </div>

                        {/* <div className='mt-8 flex xl:flex-row flex-col xl:gap-0 gap-7'>
                            <div className='flex-1'>
                                <div>
                                    {t('profile.address')}
                                </div>
                                <div className='text-description text-xs mt-2'>
                                    {t('profile.address_live')}
                                </div>
                            </div>
                            <div className='flex-1'>
                                <div className='rowTwoInput'>
                                    <Select
                                        label={t('profile.province')}
                                        items={getProvines.data?.data?.provinces.map((item: ProvinesItemType) => ({ label: item.name, value: item.id }))}
                                        onChange={(e) => setProvinesId(e.target.value)}
                                        className='bg-white border'
                                        placeholder={t('select')}
                                        value={provinesId}
                                    />
                                    <Select
                                        label={t('profile.city')}
                                        items={getCities.data?.data?.cities ? getCities.data?.data?.cities.map((item: ProvinesItemType) => ({ label: item.name, value: item.id })) : []}
                                        placeholder={t('select')}
                                        {...formik.getFieldProps('cityId')}
                                        error_text={formik.touched.cityId && formik.errors.cityId ? formik.errors.cityId : ''}
                                    />
                                </div>

                                <div className='xl:mt-7 mt-4'>
                                    <Input
                                        label={t('profile.postal_code')}
                                        {...formik.getFieldProps('postalCode')}
                                        error_text={formik.touched.postalCode && formik.errors.postalCode ? formik.errors.postalCode : ''}
                                        value={formik.values.postalCode}
                                    />
                                </div>
                                <div className='xl:mt-7 mt-4'>
                                    <Textarea
                                        label={t('profile.address')}
                                        defaultValue={formik.values.userAddress}
                                        {...formik.getFieldProps('userAddress')}
                                        error_text={formik.touched.userAddress && formik.errors.userAddress ? formik.errors.userAddress : ''}
                                    />
                                </div>

                                <div className='flex justify-end mt-5'>
                                    <Button
                                        className='xl:w-fit px-10'
                                        onClick={() => formik.handleSubmit()}
                                        isLoading={updateProfile.isPending}
                                    >
                                        <div className='flex gap-2 items-center'>
                                            <TickCircle size={20} color='white' />
                                            <div>
                                                {t('save')}
                                            </div>
                                        </div>
                                    </Button>
                                </div>

                            </div>


                        </div> */}

                        <div className='h-20 xl:hidden'></div>
                    </div>
            }

        </div>
    )
}

export default Profile