import { type FC } from 'react'
import { useParams } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { useCreateDmenuRestaurant, useDirectLogin, useGetSubscription } from './hooks/useServiceData'
import { useFormik } from 'formik'
import { DmenuCreateRestaurantType } from './types/ServiecTypes'
import * as Yup from 'yup'
import { toast } from '../../components/Toast'
import { ErrorType } from '../../helpers/types'
import Button from '../../components/Button'
import Error from '../../components/Error'
import { TickCircle } from 'iconsax-react'
import { Helmet } from 'react-helmet-async'
import GuideSlugImage from '../../assets/images/dmenu.png'

export const ManageRestaurant: FC = () => {
    const { t } = useTranslation('global')
    const { subscriptionId } = useParams()
    const createDmenuRestaurant = useCreateDmenuRestaurant()
    const getSubscription = useGetSubscription(subscriptionId || '')
    const { mutate: directLogin } = useDirectLogin()

    const handleDirectLogin = () => {
        if (!subscriptionId) {
            toast(t('errors.required') || 'شناسه اشتراک یافت نشد', 'error')
            return
        }

        directLogin(subscriptionId, {
            onSuccess: (data) => {
                const serviceLink = getSubscription?.data?.data?.userSubscription?.plan?.service?.link
                if (serviceLink && data?.data?.tokens?.accessToken?.token && data?.data?.tokens?.refreshToken?.token) {
                    window.location.href = `${serviceLink}?token=${data.data.tokens.accessToken.token}&refreshToken=${data.data.tokens.refreshToken.token}`
                } else {
                    toast('خطا در دریافت اطلاعات سرویس', 'error')
                }
            },
            onError: (error: ErrorType) => {
                toast(error.response?.data?.error?.message?.[0] || 'خطا در ورود مستقیم', 'error')
            }
        })
    }

    const formik = useFormik<DmenuCreateRestaurantType>({
        initialValues: {
            slug: '',
            userSubscriptionId: subscriptionId || ''
        },
        enableReinitialize: true,
        validationSchema: Yup.object({
            slug: Yup.string()
                .required(t('errors.required'))
                .matches(/^[a-zA-Z0-9-]+$/, 'اسلاگ باید فقط شامل حروف انگلیسی، اعداد و خط تیره باشد'),
            userSubscriptionId: Yup.string().required(t('errors.required'))
        }),
        onSubmit: (values) => {
            createDmenuRestaurant.mutate(values, {
                onSuccess: () => {
                    toast(t('success') || 'با موفقیت انجام شد', 'success')
                    formik.resetForm()
                    handleDirectLogin()
                },
                onError: (error: ErrorType) => {
                    toast(error.response?.data?.error?.message?.[0] || 'خطا در ایجاد رستوران', 'error')
                }
            })
        }
    })

    return (
        <>
            <Helmet>
                <title>{t('restaurant.manage')}</title>
            </Helmet>
            <div className='mt-4'>
                <div className='text-lg font-semibold mb-2'>
                    {t('restaurant.manage')}
                </div>

                <div className='bg-white rounded-3xl xl:p-6 p-4 xl:pb-0 pb-0 mt-8 text-sm'>
                    <div className='mt-4'>
                        <div className='mb-6'>
                            <div className='text-base font-medium mb-2'>
                                {t('restaurant.restaurant_info') || 'اطلاعات رستوران'}
                            </div>
                            <div className='text-description text-xs'>
                                {t('restaurant.enter_restaurant_info') || 'لطفا اطلاعات رستوران خود را وارد کنید'}
                            </div>
                        </div>

                        <div className='flex lg:max-w-[500px] mx-auto flex-col gap-6'>
                            <div className='w-full'>
                                <label className='text-sm font-medium mb-2 block'>
                                    {t('restaurant.slug') || 'اسلاگ'}
                                </label>
                                <div className='w-full relative mt-1'>
                                    <div className='flex items-center border border-border rounded-xl overflow-hidden bg-white hover:border-gray-400 transition-colors focus-within:border-primary focus-within:ring-2 focus-within:ring-primary/20' dir='ltr'>
                                        <div className='px-4 py-2.5 bg-gray-50 text-xs text-gray-600 border-r border-border whitespace-nowrap font-medium'>
                                            dmenu.danakcorp.com/
                                        </div>
                                        <input
                                            type='text'
                                            value={formik.values.slug}
                                            onChange={(e) => {
                                                formik.setFieldValue('slug', e.target.value)
                                            }}
                                            onBlur={formik.handleBlur}
                                            placeholder={t('restaurant.enter_slug') || 'اسلاگ را وارد کنید'}
                                            className='flex-1 h-10 text-black block px-4 text-xs border-0 focus:outline-none focus:ring-0 bg-transparent'
                                            dir='ltr'
                                        />
                                    </div>
                                    {formik.touched.slug && formik.errors.slug && (
                                        <Error errorText={formik.errors.slug} />
                                    )}
                                </div>
                            </div>

                            <div className='mt-4 flex justify-center'>
                                <Button
                                    className='xl:w-fit px-16'
                                    onClick={() => formik.handleSubmit()}
                                    isLoading={createDmenuRestaurant.isPending}
                                >
                                    <div className='flex gap-2 items-center'>
                                        <TickCircle
                                            size={24}
                                            color='white'
                                        />
                                        <div>{t('save') || 'ذخیره'}</div>
                                    </div>
                                </Button>
                            </div>

                            <div className='mt-10'>
                                <img src={GuideSlugImage} className='w-[300px] mx-auto' />
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </>
    )
}
