import { FC, useState } from 'react'
import { useTranslation } from 'react-i18next'
import SwitchComponent from '../../../components/Switch'
import Input from '../../../components/Input'
import Select from '../../../components/Select'
import UploadBoxDraggble from '../../../components/UploadBoxDraggble'
import Button from '../../../components/Button'
import { TickCircle } from 'iconsax-react'
import { useCreateServiceCategory, useGetCategoryParents, useSingleUpload } from '../hooks/useServiceData'
import { CreateServiceCategoryType, ServiceCategoryType } from '../types/ServiceTypes'
import * as Yup from 'yup'
import { useFormik } from 'formik'
import { toast } from 'react-toastify'
import { ErrorType } from '../../../helpers/types'

const CreateCategory: FC = () => {

    const { t } = useTranslation('global')
    const [file, setFile] = useState<File>()
    const getCategory = useGetCategoryParents()
    const createCategory = useCreateServiceCategory()
    const singleUpload = useSingleUpload()

    const formik = useFormik<CreateServiceCategoryType>({
        initialValues: {
            title: '',
            isActive: true,
            parentId: '',
            order: '',
        },
        validationSchema: Yup.object({
            title: Yup.string().required(t('errors.required')),
        }),
        onSubmit: async (values) => {
            if (!file) {
                toast.error(t('errors.upload_image'))
                return
            }

            const formData = new FormData()
            formData.append('file', file)
            await singleUpload.mutateAsync(formData, {
                onSuccess: (data) => {
                    values.icon = data?.data?.url
                },
                onError: (error: ErrorType) => {
                    toast.error(error.response?.data?.error?.message[0])
                }
            })

            const params = {
                ...values,
                parentId: values.parentId ? values.parentId : undefined,
                order: +values.order
            }
            createCategory.mutate(params, {
                onSuccess: () => {
                    formik.resetForm()
                    getCategory.refetch()
                    toast.success(t('success'))
                },
                onError: (error: ErrorType) => {
                    toast.error(error?.response?.data?.error?.message[0])
                }
            })
        }
    })

    return (
        <div className='bg-white p-8 w-sidebar hidden xl:block rounded-3xl overflow-hidden relative'>
            <div>
                {t('service.add_category')}
            </div>

            <div className='mt-8 flex justify-between'>
                <div className='text-sm'>
                    {t('service.status_category')}
                </div>
                <div className='flex'>
                    <SwitchComponent
                        active={formik.values.isActive}
                        onChange={(value) => formik.setFieldValue('isActive', value)}
                    />
                </div>
            </div>

            <div className='mt-8'>
                <Input
                    label={t('service.title_category')}
                    value={formik.values.title}
                    name='title'
                    onChange={formik.handleChange}
                    error_text={formik.touched.title && formik.errors.title ? formik.errors.title : ''}
                />
            </div>
            <div className='mt-6'>
                <Input
                    type='number'
                    label={t('priority')}
                    value={formik.values.order}
                    name='order'
                    onChange={formik.handleChange}
                    error_text={formik.touched.order && formik.errors.order ? formik.errors.order : ''}
                />
            </div>
            {
                getCategory.data &&
                <div className='mt-6'>
                    <Select
                        label={t('service.category_parent_2')}
                        items={getCategory.data?.data?.categories?.map((item: ServiceCategoryType) => {
                            return {
                                label: item.title,
                                value: item.id
                            }
                        })}
                        placeholder={t('select')}
                        name='parentId'
                        onChange={formik.handleChange}
                        error_text={formik.touched.parentId && formik.errors.parentId ? formik.errors.parentId : ''}
                    />
                </div>
            }


            <div className='mt-6'>
                <UploadBoxDraggble
                    label={t('service.icon_serice_category')}
                    onChange={(files) => setFile(files[0])}
                />
            </div>

            <div className='flex flex-1 justify-end items-end mt-8'>
                <Button
                    className='w-fit px-5'
                    onClick={() => formik.handleSubmit()}
                    isLoading={createCategory.isPending || singleUpload.isPending}
                >
                    <div className='flex items-center gap-2'>
                        <TickCircle
                            className='size-5'
                            color='white'
                        />
                        <div>{t('save')}</div>
                    </div>
                </Button>
            </div>
        </div>
    )
}

export default CreateCategory