import { useEffect, useState, type FC } from 'react'
import Button from '@/components/Button'
import { TickSquare } from 'iconsax-react'
import { useOrderStore } from './store/OrderStore'
import { useGetOrderDetails, useUpdateOrder } from './hooks/useOrderData'
import { toast } from '@/shared/toast'
import { useNavigate } from 'react-router-dom'
import { Paths } from '@/config/Paths'
import { extractErrorMessage } from '@/config/func'
import { useFormik } from 'formik'
import type { CreateBaseOrderType } from '../product/types/Types'
import { OrderStatusEnum } from './enum/OrderEnum'
import * as Yup from 'yup'
import Input from '@/components/Input'
import Select from '@/components/Select'
import { useGetUsers } from '../user/hooks/useUserData'
import { useParams } from 'react-router-dom'
import EditOrderComponent from './components/SingleOrderEdit'
import type { CreateOrderType } from './types/Types'

const EditOrder: FC = () => {

    const { id } = useParams()
    const { data } = useGetOrderDetails(id!)
    const navigate = useNavigate()
    const { mutate: submitOrder, isPending } = useUpdateOrder()
    const { data: users } = useGetUsers()
    const [showOrders, setShowOrders] = useState([0])
    const { items, setItems } = useOrderStore()

    const formik = useFormik<CreateBaseOrderType>({
        initialValues: {
            enableTax: true,
            estimatedDays: 0,
            paymentMethod: '',
            status: OrderStatusEnum.CREATED,
            userId: '',
        },
        validationSchema: Yup.object({
            userId: Yup.string().required('این فیلد اجباری می باشد.'),
            estimatedDays: Yup.number().required('این فیلد اجباری می باشد.'),
            paymentMethod: Yup.string().required('این فیلد اجباری می باشد.'),
        }),
        onSubmit: (values) => {
            values.estimatedDays = Number(values.estimatedDays)
            onSubmit(values)
        }
    })

    const onSubmit = (values: CreateBaseOrderType) => {
        if (items.length > 0) {
            const params = {
                ...values,
                items: items
            }
            submitOrder({ orderId: id!, params }, {
                onSuccess: () => {
                    toast('سفارش با موفقیت ویرایش شد', 'success')
                    navigate(Paths.order.list)
                },
                onError: (error) => {
                    toast(extractErrorMessage(error), 'error')
                }
            })
        } else {
            toast('حداقل یک سفارش باید اضافه کنید.', 'error')
        }
    }

    useEffect(() => {
        if (data && data?.data) {
            formik.setValues({
                enableTax: data?.data?.enableTax,
                estimatedDays: data?.data?.estimatedDays as number,
                paymentMethod: data?.data?.paymentMethod,
                status: data?.data?.status as OrderStatusEnum,
                userId: data?.data?.user.id,
            })
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [data])

    useEffect(() => {
        if (data && data?.data) {

            const items: CreateOrderType[] = []
            data?.data?.items.map((item) => {
                items.push({
                    id: item.id,
                    productId: item.product.id,
                    quantity: item.quantity,
                    attributes: item.attributes,
                    attachments: item.attachments,
                    discount: item.discount,
                    unitPrice: item.unitPrice,
                    description: item.description,
                })
            })
            setItems(items)
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [data])



    return (
        <div className='mt-5'>
            <div className='justify-between items-center flex'>
                <h1 className='text-lg font-light'>
                    ویرایش سفارش
                </h1>
                <Button
                    className='w-fit px-5'
                    onClick={() => formik.handleSubmit()}
                    isLoading={isPending}
                >
                    <div className='flex gap-2 items-center'>
                        <TickSquare size={20} color='black' />
                        <div>ذخیره سفارش</div>
                    </div>
                </Button>
            </div>

            <div className='bg-white rounded-3xl p-6 mt-8'>
                <div className='font-light'>اطلاعات  اولیه</div>

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

                    <Input
                        label='نوع پرداخت'
                        {...formik.getFieldProps('paymentMethod')}
                        error_text={formik.errors.paymentMethod && formik.touched.paymentMethod ? formik.errors.paymentMethod : ''}
                    />
                </div>

                <div className='rowTwoInput mt-6'>

                    <Select
                        items={users?.data?.map((item) => {
                            return {
                                label: item.firstName ? item.firstName + ' ' + item.lastName : item.phone,
                                value: item.id
                            }
                        }) || []}
                        label='انتخاب کاربر'
                        placeholder='انتخاب'
                        {...formik.getFieldProps('userId')}
                        error_text={formik.errors.userId && formik.touched.userId ? formik.errors.userId : ''}
                    />

                    <Select
                        label='وضعیت سفارش'
                        placeholder='انتخاب'
                        items={Object.values(OrderStatusEnum).map((item) => {
                            return {
                                label: item,
                                value: item
                            }
                        })}
                        {...formik.getFieldProps('status')}
                        error_text={formik.errors.status && formik.touched.status ? formik.errors.status : ''}
                    />
                </div>

            </div>

            {items.map((item) => {
                return (
                    <EditOrderComponent addNewItem={() => setShowOrders([...showOrders, showOrders.length])} key={item.productId} initialValues={item} />
                )
            })}

        </div>
    )
}

export default EditOrder