import Button from '@/components/Button'
import { Edit } from 'iconsax-react'
import { useEffect, type FC } from 'react'
import { useGetSectionsDetail, useUpdateSection } from './hooks/usePrintData'
import { useFormik } from 'formik'
import type { CreateSectionType } from './types/Types'
import * as Yup from 'yup'
import { toast } from '@/shared/toast'
import { useNavigate, useParams } from 'react-router-dom'
import { extractErrorMessage } from '@/config/func'
import Input from '@/components/Input'

const UpdateSection: FC = () => {

    const { id } = useParams()
    const navigate = useNavigate()
    const { data } = useGetSectionsDetail(+id!)
    const { isPending, mutate } = useUpdateSection()

    const formik = useFormik<CreateSectionType>({
        initialValues: {
            order: 1,
            title: ''
        },
        validationSchema: Yup.object({
            title: Yup.string().required('این فیلد اجباری می باشد.')
        }),
        onSubmit: (values) => {
            mutate({ id: +id!, params: values }, {
                onSuccess: () => {
                    toast('با موفقیت ثبت شد', 'success')
                    navigate(-1)
                },
                onError: (error) => {
                    toast(extractErrorMessage(error), 'error')
                }
            })
        }
    })

    useEffect(() => {

        if (data?.data) {
            formik.setValues({
                ...data?.data
            })
        }

        // 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'
                    isLoading={isPending}
                    onClick={() => formik.handleSubmit()}
                >
                    <div className='flex gap-1.5'>
                        <Edit size={18} color='black' />
                        <div className='text-[13px] font-light'>ذخیره بخش</div>
                    </div>
                </Button>
            </div>
            <div className='mt-8 bg-white p-6 rounded-3xl'>
                <div>
                    <Input
                        {...formik.getFieldProps('title')}
                        label='عنوان'
                        error_text={formik.touched.title && formik.errors.title ? formik.errors.title : ''}
                    />
                </div>
                <div className='mt-6'>
                    <Input
                        {...formik.getFieldProps('order')}
                        label='ترتیب'
                    />
                </div>
            </div>

        </div>
    )
}

export default UpdateSection