import { type FC, useState } from 'react'
import { useFormik } from 'formik'
import { type CreateWarrantyType } from './types/Types'
import * as Yup from 'yup'
import { useCreateWarranty } from './hooks/useWarrantyData'
import { useNavigate } from 'react-router-dom'
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 CreateWarranty: FC = () => {
    const navigate = useNavigate()
    const uploadSingle = useUploadSingle()
    const createWarrantyMutation = useCreateWarranty()

    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
            }

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

    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={createWarrantyMutation.isPending || uploadSingle.isPending}
                        disabled={!formik.isValid || createWarrantyMutation.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)}
                                />
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    )
}

export default CreateWarranty