import { FC, useState } from 'react'
import { useTranslation } from 'react-i18next'
import Button from '../../components/Button'
import { TickCircle } from 'iconsax-react'
import Input from '../../components/Input'
import Select from '../../components/Select'
import UploadBoxDraggble from '../../components/UploadBoxDraggble'
import { useFormik } from 'formik'
import { CreateUserType, RoleItemType } from './types/UserTypes'
import * as Yup from 'yup'
import { useSingleUpload } from '../service/hooks/useServiceData'
import { useCreateUser, useGetRoles } from './hooks/useUserData'
import { toast } from 'react-toastify'
import { ErrorType } from '../../helpers/types'
import { useNavigate } from 'react-router-dom'
import { Pages } from '../../config/Pages'

const CreateUser: FC = () => {

    const navigate = useNavigate()
    const { t } = useTranslation('global')
    const [file, setFile] = useState<File>()
    const getRoles = useGetRoles('')
    const singleUpload = useSingleUpload()
    const createUser = useCreateUser()

    const handleCreateUser = (values: CreateUserType) => {
        createUser.mutate(values, {
            onSuccess: () => {
                toast.success(t('success'))
                navigate(Pages.users.list)
            },
            onError: (error: ErrorType) => {
                toast.error(error.response?.data?.error?.message[0])
            }
        })
    }

    const formik = useFormik<CreateUserType>({
        initialValues: {
            email: '',
            firstName: '',
            lastName: '',
            password: '',
            repeatPassword: '',
            phone: '',
            profilePic: '',
            roleId: ''
        },
        validationSchema: Yup.object({
            email: Yup.string().email('Invalid email').required(t('errors.required')),
            firstName: Yup.string().required(t('errors.required')),
            lastName: Yup.string().required(t('errors.required')),
            password: Yup.string().required(t('errors.required')),
            repeatPassword: Yup.string().required(t('errors.required')),
            phone: Yup.string().required(t('errors.required')),
            roleId: Yup.string().required(t('errors.required')),
        }),
        onSubmit: async (values) => {
            if (file) {
                const formData = new FormData()
                formData.append('file', file)
                await singleUpload.mutateAsync(formData, {
                    onSuccess: (data) => {
                        values.profilePic = data?.data?.url
                        handleCreateUser(values)
                    },
                    onError: (error: ErrorType) => {
                        toast.error(error.response?.data?.error?.message[0])
                    }
                })
            } else {
                values.profilePic = undefined
                handleCreateUser(values)
            }
        }
    })

    return (
        <div className='mt-4'>
            <div className='flex justify-between items-center'>
                <div>
                    {t('service.cateory_services')}
                </div>
                <Button
                    className='w-fit px-8'
                    onClick={() => formik.handleSubmit()}
                    isLoading={createUser.isPending}
                >
                    <div className='flex gap-2'>
                        <TickCircle
                            className='size-5'
                            color='white'
                        />
                        <div className='text-sm'>
                            {t('user.submit_user')}
                        </div>
                    </div>
                </Button>
            </div>

            <div className='flex gap-6 mt-9'>
                <div className='flex-1  bg-white py-10 xl:px-10 px-5 rounded-3xl'>
                    <div>
                        {t('user.info_user')}
                    </div>

                    <div className='rowTwoInput mt-8'>
                        <Input
                            label={t('user.name')}
                            {...formik.getFieldProps('firstName')}
                            error_text={formik.touched.firstName && formik.errors.firstName ? formik.errors.firstName : ''}
                        />
                        <Input
                            label={t('user.family')}
                            {...formik.getFieldProps('lastName')}
                            error_text={formik.touched.lastName && formik.errors.lastName ? formik.errors.lastName : ''}
                        />
                    </div>
                    <div className='rowTwoInput mt-8'>
                        {/* <Input
                            label={t('user.title_job')}
                        /> */}
                        <Select
                            label={t('user.role')}
                            placeholder={t('select')}
                            items={getRoles.data?.data?.roles?.map((item: RoleItemType) => {
                                return {
                                    label: item.name,
                                    value: item.id
                                }
                            })}
                            {...formik.getFieldProps('roleId')}
                            error_text={formik.touched.roleId && formik.errors.roleId ? formik.errors.roleId : ''}
                        />
                    </div>

                    <div className='rowTwoInput mt-8'>
                        <Input
                            label={t('user.email')}
                            {...formik.getFieldProps('email')}
                            error_text={formik.touched.email && formik.errors.email ? formik.errors.email : ''}
                        />
                        <Input
                            label={t('user.phone_number')}
                            {...formik.getFieldProps('phone')}
                            error_text={formik.touched.phone && formik.errors.phone ? formik.errors.phone : ''}
                        />
                    </div>

                </div>

                <div className='bg-white p-8 w-sidebar hidden xl:block rounded-3xl overflow-hidden relative'>
                    <Input
                        label={t('user.password')}
                        {...formik.getFieldProps('password')}
                        error_text={formik.touched.password && formik.errors.password ? formik.errors.password : ''}
                        type='password'
                    />

                    <div className='mt-8'>
                        <Input
                            label={t('user.reapeat_password')}
                            {...formik.getFieldProps('repeatPassword')}
                            error_text={formik.touched.repeatPassword && formik.errors.repeatPassword ? formik.errors.repeatPassword : ''}
                            type='password'
                        />
                    </div>

                    <div className='mt-8'>
                        <div className='text-sm'>
                            {t('user.image')}
                        </div>
                        <div className='mt-2'>
                            <UploadBoxDraggble
                                label={t('user.image')}
                                onChange={(file) => setFile(file[0])}
                            />
                        </div>
                    </div>
                </div>
            </div>

        </div>
    )
}

export default CreateUser