import { useFormik } from 'formik'
import { useEffect, type FC } from 'react'
import type { CreateFieldType } from './types/Types'
import { FieldTypeEnum } from './enum/Enum'
import * as Yup from 'yup'
import Button from '@/components/Button'
import { AddSquare } from 'iconsax-react'
import Input from '@/components/Input'
import Select from '@/components/Select'
import SwitchComponent from '@/components/Switch'
import { useGetFieldDetail, useUpdateField } from './hooks/useFormBuilderData'
import { useNavigate, useParams } from 'react-router-dom'
import { toast } from 'react-toastify'
import { extractErrorMessage } from '@/config/func'

const FormBuilderUpdate: FC = () => {

    const { id } = useParams()
    const navigate = useNavigate()
    const { data, refetch } = useGetFieldDetail(Number(id))
    const { mutate: createField, isPending } = useUpdateField()

    const formik = useFormik<CreateFieldType>({
        initialValues: {
            name: '',
            isRequired: true,
            order: 1,
            type: FieldTypeEnum.text,
            entityType: '',
            multiple: false
        },
        validationSchema: Yup.object({
            name: Yup.string().required('این فیلد اجباری می باشد')
        }),
        onSubmit: (values) => {
            createField({ id: Number(id), params: values }, {
                onSuccess: () => {
                    toast.success('با موفقیت ذخیره شد')
                    refetch()
                    navigate(-1)
                },
                onError: (error) => {
                    toast.error(extractErrorMessage(error))
                }
            })
        }
    })

    useEffect(() => {

        if (data) {
            formik.setValues({
                isRequired: data?.data?.isRequired,
                name: data?.data?.name,
                order: data?.data?.order,
                type: data?.data?.type,
                entityType: data?.data?.entityType,
                multiple: data?.data?.multiple
            })
        }

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


    return (
        <div className='mt-5'>
            <div className='flex justify-between items-center'>

                <h1 className='text-lg font-light'>ویرایش فیلد</h1>
                <Button
                    className='w-fit px-6'
                    onClick={() => formik.handleSubmit()}
                    isLoading={isPending}
                >
                    <div className='flex gap-1.5'>
                        <AddSquare size={18} color='black' />
                        <div className='text-[13px] font-light'>ویرایش فیلد</div>
                    </div>
                </Button>
            </div>

            <div className='mt-8 bg-white p-6 rounded-3xl flex-1'>
                <div className='rowTwoInput'>
                    <Input
                        label='نام فیلد'
                        {...formik.getFieldProps('name')}
                        error_text={formik.touched.name && formik.errors.name ? formik.errors.name : ''}
                    />

                    <Select
                        label='نوع'
                        items={[
                            {
                                label: 'متن',
                                value: FieldTypeEnum.text
                            },
                            {
                                label: 'چک باکس',
                                value: FieldTypeEnum.checkbox
                            },
                            {
                                label: 'تاریخ',
                                value: FieldTypeEnum.date
                            },
                            {
                                label: 'عدد',
                                value: FieldTypeEnum.number
                            },
                            {
                                label: 'رادیو',
                                value: FieldTypeEnum.radio
                            },
                            {
                                label: 'کامبوباکس',
                                value: FieldTypeEnum.select
                            },
                            {
                                label: 'متن بلند',
                                value: FieldTypeEnum.textarea
                            },
                        ]}
                        {...formik.getFieldProps('type')}
                    />
                </div>

                <div className='mt-6'>
                    <Input
                        label='ترتیب اولویت'
                        {...formik.getFieldProps('order')}
                    />
                </div>

                <div className='mt-6'>
                    <SwitchComponent
                        active={formik.values.isRequired}
                        onChange={(value) => formik.setFieldValue('isRequired', value)}
                        label='اجباری'
                    />
                </div>
            </div>

        </div>
    )
}

export default FormBuilderUpdate