import { type FC, useMemo } from 'react'
import { useFormik } from 'formik'
import * as Yup from 'yup'
import { TickCircle } from 'iconsax-react'
import { toast } from 'react-toastify'
import { useNavigate, useParams } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import Button from '@/components/Button'
import Input from '@/components/Input'
import Select from '@/components/Select'
import Switch from '@/components/Switch'
import Textarea from '@/components/Textarea'
import type { CreateRestaurantPaymentMethodType } from './types/Types'
import { useGetRestaurantPaymentMethod, useUpdateRestaurantPaymentMethod } from './hooks/usePaymentMethodData'
import { PaymentMethodEnum, PaymentGatewayEnum } from './enum/Enum'
import { Pages } from '@/config/Pages'
import type { ErrorType } from '@/helpers/types'
import { extractErrorMessage } from '@/config/func'

const UpdatePaymentMethod: FC = () => {
    const { t } = useTranslation('global')
    const navigate = useNavigate()
    const { id } = useParams<{ id: string }>()
    const { mutate: updateRestaurantPaymentMethod, isPending } = useUpdateRestaurantPaymentMethod()
    const { data: paymentMethodData, isLoading } = useGetRestaurantPaymentMethod(id || '')

    const paymentMethods = [
        { label: t(`payment.${PaymentMethodEnum.Online}`), value: PaymentMethodEnum.Online },
        { label: t(`payment.${PaymentMethodEnum.Cash}`), value: PaymentMethodEnum.Cash },
        { label: t(`payment.${PaymentMethodEnum.Wallet}`), value: PaymentMethodEnum.Wallet },
    ]

    const paymentGateways = [
        { label: t(`payment.${PaymentGatewayEnum.ZarinPal}`), value: PaymentGatewayEnum.ZarinPal },
    ]

    const initialValues = useMemo<CreateRestaurantPaymentMethodType>(() => {
        if (paymentMethodData?.data) {
            const data = paymentMethodData.data as CreateRestaurantPaymentMethodType & { id: string }
            return {
                method: data.method || '',
                gateway: data.gateway || '',
                description: data.description || '',
                enabled: data.enabled ?? true,
                order: data.order || 0,
                merchantId: data.merchantId || '',
            }
        }
        return {
            method: '',
            gateway: '',
            description: '',
            enabled: true,
            order: 0,
            merchantId: '',
        }
    }, [paymentMethodData])

    const formik = useFormik<CreateRestaurantPaymentMethodType>({
        initialValues,
        enableReinitialize: true,
        validationSchema: Yup.object().shape({
            method: Yup.string().required('روش پرداخت الزامی است'),
            gateway: Yup.string().when('method', {
                is: PaymentMethodEnum.Online,
                then: (schema) => schema.required('درگاه پرداخت الزامی است'),
                otherwise: (schema) => schema.notRequired(),
            }),
            description: Yup.string().required('توضیحات الزامی است'),
            enabled: Yup.boolean(),
            order: Yup.number().required('ترتیب الزامی است').min(0, 'ترتیب باید مثبت باشد'),
            merchantId: Yup.string().when('method', {
                is: PaymentMethodEnum.Online,
                then: (schema) => schema.required('شناسه مرچنت الزامی است'),
                otherwise: (schema) => schema.notRequired(),
            }),
        }),
        onSubmit: (values) => {
            if (!id) return

            const submitValues: CreateRestaurantPaymentMethodType = {
                method: values.method,
                description: values.description,
                enabled: values.enabled,
                order: values.order,
                ...(values.method === PaymentMethodEnum.Online
                    ? {
                        gateway: values.gateway,
                        merchantId: values.merchantId,
                    }
                    : {}),
            }

            updateRestaurantPaymentMethod(
                { id, params: submitValues },
                {
                    onSuccess: () => {
                        toast.success('روش پرداخت با موفقیت ویرایش شد')
                        navigate(Pages.payment_methods.list)
                    },
                    onError: (error: ErrorType) => {
                        toast.error(extractErrorMessage(error))
                    },
                }
            )
        },
    })

    if (isLoading) {
        return (
            <div className='mt-5'>
                <div className='text-lg font-light'>در حال بارگذاری...</div>
            </div>
        )
    }

    if (!paymentMethodData?.data) {
        return (
            <div className='w-full mt-4 flex justify-center items-center'>
                <div>روش پرداخت یافت نشد</div>
            </div>
        )
    }

    return (
        <div className='mt-5'>
            <div className='flex w-full justify-between items-center'>
                <div className='text-lg font-light'>
                    ویرایش روش پرداخت
                </div>
                <div>
                    <Button
                        className='px-5'
                        onClick={() => formik.handleSubmit()}
                        isloading={isPending}
                    >
                        <div className='flex gap-2 items-center'>
                            <TickCircle className='size-5' color='white' />
                            <div>ثبت تغییرات</div>
                        </div>
                    </Button>
                </div>
            </div>

            <div className='mt-6'>
                <div className='bg-white rounded-3xl p-6'>
                    <div className='mb-4'>
                        <Select
                            label='روش پرداخت'
                            name='method'
                            value={formik.values.method}
                            onChange={formik.handleChange}
                            items={paymentMethods}
                            placeholder='روش پرداخت را انتخاب کنید'
                            error_text={formik.touched.method && formik.errors.method ? formik.errors.method : ''}
                        />
                    </div>
                    {formik.values.method === PaymentMethodEnum.Online && (
                        <>
                            <div className='mt-6'>
                                <Select
                                    label='درگاه پرداخت'
                                    name='gateway'
                                    value={formik.values.gateway}
                                    onChange={formik.handleChange}
                                    items={paymentGateways}
                                    placeholder='درگاه پرداخت را انتخاب کنید'
                                    error_text={formik.touched.gateway && formik.errors.gateway ? formik.errors.gateway : ''}
                                />
                            </div>
                            <div className='mt-6'>
                                <Input
                                    label='شناسه مرچنت'
                                    name='merchantId'
                                    value={formik.values.merchantId}
                                    onChange={formik.handleChange}
                                    error_text={formik.touched.merchantId && formik.errors.merchantId ? formik.errors.merchantId : ''}
                                />
                            </div>
                        </>
                    )}
                    <div className='mt-6'>
                        <Textarea
                            label='توضیحات'
                            name='description'
                            value={formik.values.description}
                            onChange={formik.handleChange}
                            error_text={formik.touched.description && formik.errors.description ? formik.errors.description : ''}
                        />
                    </div>
                    <div className='mt-6'>
                        <Input
                            label='ترتیب'
                            name='order'
                            type='number'
                            value={formik.values.order ?? ''}
                            onChange={(e) => {
                                const value = e.target.value === '' ? 0 : Number(e.target.value)
                                formik.setFieldValue('order', value)
                            }}
                            error_text={formik.touched.order && formik.errors.order ? formik.errors.order : ''}
                        />
                    </div>
                    <div className='mt-6'>
                        <Switch
                            active={formik.values.enabled}
                            onChange={(value) => formik.setFieldValue('enabled', value)}
                            label='فعال'
                        />
                    </div>
                </div>
            </div>
        </div>
    )
}

export default UpdatePaymentMethod
