import { type FC, useState, useEffect } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import { useFormik } from 'formik'
import { type CreateWarrantyType } from './types/Types'
import * as Yup from 'yup'
import { useGetWarrantyById, useUpdateWarranty } from './hooks/useWarrantyData'
import Input from '../../components/Input'
import Button from '../../components/Button'
import { TickCircle } from 'iconsax-react'
import { useUploadSingle } from '../uploader/hooks/useUploaderData'
import UploadBoxDraggble from '@/components/UploadBoxDraggble'
import { toast } from 'react-toastify'
import { extractErrorMessage } from '@/helpers/utils'
import { Pages } from '@/config/Pages'

const UpdateWarranty: FC = () => {
    const navigate = useNavigate()
    const { id } = useParams<{ id: string }>()
    const uploadSingle = useUploadSingle()
    const { data: warrantyDetail, isLoading: warrantyDetailLoading, error: warrantyDetailError } = useGetWarrantyById(id!)
    const warranty = warrantyDetail?.results.warranty
    const updateWarrantyMutation = useUpdateWarranty()

    const [logoFile, setLogoFile] = useState<File[]>([])

    const formik = useFormik<CreateWarrantyType>({
        initialValues: {
            name: '',
            duration: '',
            logoUrl: '',
        },
        validationSchema: Yup.object({
            name: Yup.string().required('عنوان گارانتی الزامی است'),
            duration: Yup.string().required('مدت زمان گارانتی الزامی است'),
        }),
        onSubmit: async (values) => {
            let logoUrl = values.logoUrl

            if (logoFile.length > 0) {
                const logoResponse = await uploadSingle.mutateAsync(logoFile[0])
                logoUrl = logoResponse.results?.url?.url || ''
            }

            const submitData = {
                ...values,
                logoUrl
            }

            updateWarrantyMutation.mutate({ id: id!, params: submitData }, {
                onSuccess: () => {
                    toast.success('گارانتی با موفقیت بروزرسانی شد')
                    navigate(Pages.products.warranty.list)
                },
                onError: (error) => {
                    toast.error(extractErrorMessage(error))
                }
            })
        },
    })

    useEffect(() => {
        if (warranty) {
            formik.setValues({
                name: warranty.name,
                duration: warranty.duration,
                logoUrl: warranty.logoUrl,
            })
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [warranty])

    if (warrantyDetailLoading) {
        return <div>در حال بارگذاری...</div>
    }

    if (warrantyDetailError) {
        return <div>خطا در بارگذاری داده‌ها</div>
    }

    return (
        <div className='mt-4'>
            <div className='flex justify-between items-center'>
                <div className='flex items-center gap-3'>
                    <h1>ویرایش گارانتی</h1>
                </div>
                <div>
                    <Button
                        className='px-6'
                        onClick={() => formik.handleSubmit()}
                        isLoading={updateWarrantyMutation.isPending || uploadSingle.isPending}
                        disabled={!formik.isValid || updateWarrantyMutation.isPending || uploadSingle.isPending}
                    >
                        <div className='flex gap-2 items-center'>
                            <TickCircle size={16} color='#fff' />
                            <div>بروزرسانی گارانتی</div>
                        </div>
                    </Button>
                </div>
            </div>

            <div className='flex gap-6 xl:mt-8 mt-6'>
                {/* اطلاعات اصلی */}
                <div className='flex-1 text-sm bg-white py-8 xl:px-10 px-6 rounded-3xl'>
                    <h2 className='text-lg font-medium mb-6'>اطلاعات اصلی</h2>

                    <div className='space-y-6'>
                        <div className='grid grid-cols-1 md:grid-cols-2 gap-6'>
                            <Input
                                label='عنوان گارانتی'
                                placeholder='مثال: گارانتی طلایی'
                                {...formik.getFieldProps('name')}
                                error_text={formik.touched.name && formik.errors.name ? formik.errors.name : ''}
                            />
                            <Input
                                label='مدت زمان گارانتی'
                                placeholder='مثال: 24 ماه'
                                {...formik.getFieldProps('duration')}
                                error_text={formik.touched.duration && formik.errors.duration ? formik.errors.duration : ''}
                            />
                        </div>
                    </div>
                </div>

                {/* فایل‌ها */}
                <div className='w-80 space-y-6'>
                    <div className='text-sm bg-white py-8 px-6 rounded-3xl'>
                        <h2 className='text-lg font-medium mb-6'>فایل‌ها</h2>

                        <div className='space-y-6'>
                            <div>
                                <UploadBoxDraggble
                                    label='لوگو گارانتی'
                                    isMultiple={false}
                                    onChange={(files) => setLogoFile(files)}
                                    preview={warranty?.logoUrl ? [warranty.logoUrl] : []}
                                />
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    )
}

export default UpdateWarranty