import { useState, type FC } from 'react'
import { useFormik } from 'formik'
import * as Yup from 'yup'
import Input from '@/components/Input'
import Select from '@/components/Select'
import UploadBox from '@/components/UploadBox'
import Button from '@/components/Button'
import { useMultiUpload } from '@/pages/uploader/hooks/useUploader'
import type { ConvertToOrderItemType } from './types/Types'
import { useConverToOrder, useGetProducts } from './hooks/useOrderData'
import { useGetCategory } from '@/pages/product/hooks/useProductData'
import { useGetUsers } from '@/pages/user/hooks/useUserData'
import { useSearchParams } from 'react-router-dom'

const getInitialValues = (invoiceItemId: string | null): ConvertToOrderItemType => ({
    invoiceItemId: invoiceItemId ?? '',
    productId: '',
    userId: '',
    typeId: '',
    estimatedDays: 0,
    title: '',
    attachments: [],
})

const getValidationSchema = (invoiceItemId: string | null) =>
    Yup.object({
        invoiceItemId: Yup.string(),
        productId: invoiceItemId ? Yup.string() : Yup.string().required('انتخاب محصول اجباری است.'),
        userId: invoiceItemId ? Yup.string() : Yup.string().required('انتخاب کاربر اجباری است.'),
        typeId: Yup.string().required('انتخاب نوع اجباری است.'),
        estimatedDays: Yup.number().required('تخمین روز اجباری است.').min(0, 'باید عدد مثبت باشد'),
        title: Yup.string().required('عنوان اجباری است.'),
    })

const ConvertToOrders: FC = () => {

    const [searchParams] = useSearchParams()
    const invoiceItemId = searchParams.get('invoiceItemId')
    const multiUpload = useMultiUpload()
    const [attachmentFiles, setAttachmentFiles] = useState<File[]>([])
    const { data: categories } = useGetCategory()
    const { data: users } = useGetUsers()
    const { data: products } = useGetProducts()

    const { mutate: converToOrder, isPending } = useConverToOrder()

    const formik = useFormik<ConvertToOrderItemType>({
        initialValues: getInitialValues(invoiceItemId),
        validationSchema: getValidationSchema(invoiceItemId),
        enableReinitialize: true,
        onSubmit: async (values) => {
            const attachments: string[] = [...values.attachments]

            if (attachmentFiles.length > 0) {
                const result = await multiUpload.mutateAsync(attachmentFiles)
                result?.data?.forEach((item) => {
                    attachments.push(item.url)
                })
            }

            const payload: ConvertToOrderItemType = {
                ...values,
                invoiceItemId: invoiceItemId ?? values.invoiceItemId ?? '',
                productId: invoiceItemId ? undefined : values.productId,
                userId: invoiceItemId ? undefined : values.userId,
                estimatedDays: Number(values.estimatedDays),
                attachments,
            }

            await converToOrder(payload)
        },
    })

    return (
        <div className="mt-5">
            <h1 className="text-lg font-light">تبدیل به سفارش</h1>

            <div className="bg-white rounded-3xl p-6 mt-8">
                <form
                    onSubmit={formik.handleSubmit}
                    className="space-y-6"
                >
                    {!invoiceItemId && (
                        <div className="rowTwoInput">
                            <Select
                                items={
                                    users?.data?.map((item) => ({
                                        label: item.firstName ? `${item.firstName} ${item.lastName}` : item.phone,
                                        value: item.id,
                                    })) ?? []
                                }
                                label="کاربر"
                                placeholder="انتخاب کاربر"
                                {...formik.getFieldProps('userId')}
                                error_text={
                                    formik.touched.userId && formik.errors.userId ? formik.errors.userId : ''
                                }
                            />
                            <Select
                                items={
                                    products?.data?.map((item) => ({
                                        label: item.title,
                                        value: String(item.id),
                                    })) ?? []
                                }
                                label="محصول"
                                placeholder="انتخاب محصول"
                                {...formik.getFieldProps('productId')}
                                error_text={
                                    formik.touched.productId && formik.errors.productId
                                        ? formik.errors.productId
                                        : ''
                                }
                            />
                        </div>
                    )}

                    <div className="rowTwoInput">

                        <Select
                            items={
                                categories?.data?.map((item) => ({
                                    label: item.title,
                                    value: String(item.id),
                                })) ?? []
                            }
                            label="نوع"
                            placeholder="انتخاب نوع"
                            {...formik.getFieldProps('typeId')}
                            error_text={
                                formik.touched.typeId && formik.errors.typeId ? formik.errors.typeId : ''
                            }
                        />
                    </div>

                    <div className="rowTwoInput">
                        <Input
                            label="تخمین روز"
                            type="number"
                            {...formik.getFieldProps('estimatedDays')}
                            error_text={
                                formik.touched.estimatedDays && formik.errors.estimatedDays
                                    ? formik.errors.estimatedDays
                                    : ''
                            }
                        />

                        <Input
                            label="عنوان"
                            {...formik.getFieldProps('title')}
                            error_text={
                                formik.touched.title && formik.errors.title ? formik.errors.title : ''
                            }
                        />
                    </div>

                    <div>
                        <UploadBox
                            label="پیوست‌ها"
                            isMultiple
                            onChange={setAttachmentFiles}
                        />
                    </div>

                    <div className="flex justify-end">
                        <Button type="submit" isLoading={multiUpload.isPending || isPending}>
                            ثبت
                        </Button>
                    </div>
                </form>
            </div>
        </div>
    )
}

export default ConvertToOrders
