import { type FC, useState } from 'react'
import { useFormik } from 'formik'
import * as Yup from 'yup'
import { TickCircle } from 'iconsax-react'
import { toast } from 'react-toastify'
import Button from '@/components/Button'
import CreateProductSidebar from './components/CreateProductSidebar'
import BasicInfoSection from './components/BasicInfoSection'
import type { CreateProductType } from './types/Types'
import { useCreateProduct, useGetCategories } from './hooks/useProductData'
import { useMultipleUpload } from '../uploader/hooks/useUploaderData'
import { Pages } from '@/config/Pages'
import type { ErrorType } from '@/helpers/types'



const CreateProduct: FC = () => {

    const { data } = useGetCategories();
    const [isActive, setIsActive] = useState<boolean>(true)
    const [isSpecial, setIsSpecial] = useState<boolean>(false)
    const [imageFiles, setImageFiles] = useState<File[]>([])
    const { mutate: createProduct, isPending } = useCreateProduct()
    const { mutate: multipleUpload, isPending: isUploading } = useMultipleUpload()

    const categories = data?.data ?? []

    const formik = useFormik<CreateProductType>({
        initialValues: {
            categoryId: '',
            title: '',
            attribute: '',
            variants: [],
            desc: '',
            price: 0,
            isActive: true,
            images: [],
            discount: 0,
            isSpecialOffer: false,
            order: 0,
            stock: undefined,
            maxPurchaseQuantity: undefined
        },
        validationSchema: Yup.object().shape({
            title: Yup.string().required('نام کالا الزامی است'),
            categoryId: Yup.string().required('دسته‌بندی الزامی است'),
            price: Yup.number().required('قیمت الزامی است').min(0, 'قیمت باید مثبت باشد'),
            discount: Yup.number().min(0, 'تخفیف باید مثبت باشد'),
            attribute: Yup.string(),
            variants: Yup.array().of(
                Yup.object().shape({
                    id: Yup.string(),
                    value: Yup.string(),
                    price: Yup.number().min(0)
                })
            )
        }),
        onSubmit: (values) => {
            const submitProduct = (imageUrls: string[] = []) => {
                const variants =
                    values.variants.length > 0
                        ? values.variants
                        : [{ value: '', price: values.price, ...(values.stock !== undefined && values.stock !== null && { stock: values.stock }) }]
                const productData: CreateProductType = {
                    ...values,
                    variants,
                    isActive,
                    isSpecialOffer: isSpecial,
                    images: imageUrls
                }

                createProduct(productData, {
                    onSuccess: () => {
                        toast.success('کالا با موفقیت ایجاد شد')
                        window.location.href = Pages.products.list
                    },
                    onError: (error: ErrorType) => {
                        toast.error(error?.response?.data?.error?.message[0] || 'خطا در ایجاد کالا')
                    }
                })
            }

            if (imageFiles.length > 0) {
                multipleUpload(imageFiles, {
                    onSuccess: (response) => {
                        const imageUrls = response?.data?.map(item => item.url) || []
                        submitProduct(imageUrls)
                    },
                    onError: (error: ErrorType) => {
                        toast.error(error?.response?.data?.error?.message[0] || 'خطا در آپلود تصاویر')
                    }
                })
            } else {
                submitProduct()
            }
        }
    })

    return (
        <div className='w-full mt-4'>
            <div className='flex flex-col sm:flex-row w-full justify-between items-start sm:items-center gap-4'>
                <div className='text-lg font-light'>
                    کالای جدید
                </div>
                <div>
                    <Button
                        className='px-5 w-full sm:w-auto'
                        onClick={() => formik.handleSubmit()}
                        isloading={isPending || isUploading}
                    >
                        <div className='flex gap-2 items-center'>
                            <TickCircle className='size-5' color='white' />
                            <div>ثبت کالا</div>
                        </div>
                    </Button>
                </div>
            </div>

            <div className='flex flex-col lg:flex-row gap-6 mt-6'>
                <div className='flex-1'>
                    <div className='bg-white py-6 sm:py-8 xl:px-10 px-4 rounded-3xl'>
                        <BasicInfoSection formik={formik} categories={categories} />
                    </div>
                </div>

                <div className='w-full lg:w-auto'>
                    <CreateProductSidebar
                        isActive={isActive}
                        isSpecial={isSpecial}
                        onChangeActive={setIsActive}
                        onChangeSpecial={setIsSpecial}
                        onChangeImages={setImageFiles}
                    />
                </div>
            </div>
        </div>
    )
}

export default CreateProduct
