import { Edit, TickCircle } from 'iconsax-react'
import { FC, useEffect, useState } from 'react'
import DefaulModal from '../../../components/DefaulModal'
import { useGetCategoryDetail, useGetCategoryParents, useSingleUpload, useUpdateCategory } from '../hooks/useServiceData'
import Input from '../../../components/Input'
import { CreateServiceCategoryType, ServiceCategoryType } from '../types/ServiceTypes'
import * as Yup from 'yup'
import { useFormik } from 'formik'
import { toast } from 'react-toastify'
import { useTranslation } from 'react-i18next'
import { ErrorType } from '../../../helpers/types'
import Select from '../../../components/Select'
import UploadBox from '../../../components/UploadBox'
import Button from '../../../components/Button'

type Props = {
    id: string,
    refetch: () => void
}

const UpdateCategory: FC<Props> = (props) => {

    const { t } = useTranslation('global')
    const [showModal, setShowModal] = useState<boolean>(false)
    const [file, setFile] = useState<File>()
    const getCategoryDetail = useGetCategoryDetail(props.id, showModal)
    const singleUpload = useSingleUpload()
    const getCategory = useGetCategoryParents()
    const updateCategory = useUpdateCategory(props.id)

    const formik = useFormik<CreateServiceCategoryType>({
        initialValues: {
            title: '',
            isActive: true,
            parentId: ''
        },
        validationSchema: Yup.object({
            title: 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.icon = data?.data?.url
                    },
                    onError: (error: ErrorType) => {
                        toast.error(error.response?.data?.error?.message[0])
                    }
                })
            }



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

    useEffect(() => {

        if (getCategoryDetail.data) {
            const data = getCategoryDetail.data?.data?.category
            formik.setValues({
                title: data?.title,
                parentId: data?.parentId,
                isActive: data?.isActive
            })
        }

        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [getCategoryDetail.data])


    return (
        <div>
            <Edit onClick={() => setShowModal(true)} size={20} color='#888888' />

            <DefaulModal
                open={showModal}
                close={() => setShowModal(false)}
                isHeader
                title_header='ویرایش دسته بندی'
            >
                <div className='mt-5'>
                    <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 : ''}
                        className='bg-white bg-opacity-40'
                    />
                </div>

                {
                    getCategory.data &&
                    <div className='mt-5'>
                        <Select
                            className='bg-white bg-opacity-40'
                            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'
                            value={formik.values.parentId}
                            onChange={formik.handleChange}
                            error_text={formik.touched.parentId && formik.errors.parentId ? formik.errors.parentId : ''}
                        />
                    </div>
                }

                <div className='mt-5'>
                    <UploadBox
                        label='آیکون جدید'
                        onChange={(file) => setFile(file[0])}
                    />
                </div>

                <div className='mt-10 border-t border-border pt-5 flex justify-end'>
                    <div className='flex gap-5 items-center'>
                        <Button
                            className='w-[150px] bg-white bg-opacity-15 text-description'
                            label={t('plan.cancel')}
                            onClick={() => setShowModal(false)}
                        />

                        <Button
                            onClick={() => formik.handleSubmit()}
                        >
                            <div className='flex gap-2'>
                                <TickCircle
                                    size={20}
                                    color='white'
                                />
                                <div>
                                    {t('save')}
                                </div>
                            </div>
                        </Button>
                    </div>
                </div>

            </DefaulModal>
        </div>
    )
}

export default UpdateCategory