import { useFormik } from 'formik'
import { FC, useEffect } from 'react'
import { UpdateShopType, ShopResponse } from '../types/Types'
import { useParams, useNavigate } from 'react-router-dom'
import { useGetShop, useUpdateShop } from '../hooks/useIconData'
import { useTranslation } from 'react-i18next'
import Input from '../../../components/Input'
import Select from '../../../components/Select'
import SwitchComponent from '../../../components/Switch'
import Button from '../../../components/Button'
import DatePickerComponent from '../../../components/DatePicker'
import PageLoading from '../../../components/PageLoading'
import { toast } from '../../../components/Toast';
import { ErrorType } from '../../../helpers/types'
import { TickCircle } from 'iconsax-react'
import { Pages } from '../../../config/Pages'
import moment from 'moment-jalaali'
import { useQueryClient } from '@tanstack/react-query'

const UpdateShop: FC = () => {

    const { id } = useParams()
    const { t } = useTranslation('global')
    const navigate = useNavigate()
    const queryClient = useQueryClient()
    const { data: shopData, isLoading } = useGetShop(id || '')
    const updateShop = useUpdateShop()

    const shop = (shopData as ShopResponse | undefined)?.data

    const formik = useFormik<UpdateShopType>({
        initialValues: {
            name: undefined,
            slug: undefined,
            establishedYear: undefined,
            phone: undefined,
            plan: undefined,
            subscriptionId: undefined,
            subscriptionEndDate: undefined,
            subscriptionStartDate: undefined,
            isActive: undefined,
        },
        onSubmit: (values) => {
            if (!id) return

            const params: UpdateShopType = {
                ...values,
                subscriptionStartDate: values.subscriptionStartDate
                    ? moment(values.subscriptionStartDate, 'jYYYY/jMM/jDD').format('YYYY-MM-DD')
                    : undefined,
                subscriptionEndDate: values.subscriptionEndDate
                    ? moment(values.subscriptionEndDate, 'jYYYY/jMM/jDD').format('YYYY-MM-DD')
                    : undefined,
            }

            updateShop.mutate(
                { id, params },
                {
                    onSuccess: () => {
                        toast(t('success'), 'success')
                        queryClient.invalidateQueries({ queryKey: ['shops'] })
                        queryClient.invalidateQueries({ queryKey: ['shop', id] })
                        navigate(Pages.dkala.shops.list)
                    },
                    onError: (error: ErrorType) => {
                        toast(error.response?.data?.error?.message?.[0] || 'خطا در بروزرسانی فروشگاه', 'error')
                    }
                }
            )
        }
    })

    useEffect(() => {
        if (shop) {
            formik.setValues({
                name: shop.name || undefined,
                slug: shop.slug || undefined,
                establishedYear: shop.establishedYear || undefined,
                phone: shop.phone || undefined,
                plan: shop.plan || undefined,
                subscriptionId: shop.subscriptionId || undefined,
                subscriptionEndDate: shop.subscriptionEndDate || undefined,
                subscriptionStartDate: shop.subscriptionStartDate || undefined,
                isActive: shop.isActive,
            })
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [shop])

    const planOptions = [
        { value: 'base', label: 'پایه' },
        { value: 'premium', label: 'پرمیوم' },
    ]

    if (isLoading) {
        return <PageLoading />
    }

    return (
        <div className='w-full mt-4'>
            <div className='flex w-full justify-between items-center'>
                <div>
                    {t('shop.list_shop')}
                </div>
                <div>
                    <Button
                        className='px-5'
                        onClick={() => formik.handleSubmit()}
                        isLoading={updateShop.isPending}
                    >
                        <div className='flex gap-2'>
                            <TickCircle
                                className='size-5'
                                color='#fff'
                            />
                            <div>{t('save')}</div>
                        </div>
                    </Button>
                </div>
            </div>

            <div className='flex gap-6 mt-10'>
                <div className='flex-1'>
                    <div className='flex-1 bg-white py-8 xl:px-10 px-4 rounded-3xl'>
                        <div className='rowTwoInput'>
                            <Input
                                label={t('shop.name')}
                                {...formik.getFieldProps('name')}
                                error_text={formik.touched.name && formik.errors.name ? formik.errors.name : ''}
                            />

                            <Input
                                label={t('shop.slug')}
                                {...formik.getFieldProps('slug')}
                                error_text={formik.touched.slug && formik.errors.slug ? formik.errors.slug : ''}
                            />
                        </div>

                        <div className='mt-8 rowTwoInput'>
                            <Input
                                label={t('shop.phone')}
                                {...formik.getFieldProps('phone')}
                                error_text={formik.touched.phone && formik.errors.phone ? formik.errors.phone : ''}
                            />

                            <Input
                                label={t('shop.established_year')}
                                type='number'
                                {...formik.getFieldProps('establishedYear')}
                                error_text={formik.touched.establishedYear && formik.errors.establishedYear ? formik.errors.establishedYear : ''}
                            />
                        </div>

                        <div className='mt-8 rowTwoInput'>
                            <Select
                                label={t('shop.plan')}
                                items={planOptions}
                                {...formik.getFieldProps('plan')}
                                placeholder={t('select')}
                                error_text={formik.touched.plan && formik.errors.plan ? formik.errors.plan : ''}
                            />

                            <Input
                                label={t('shop.subscription_id')}
                                {...formik.getFieldProps('subscriptionId')}
                                error_text={formik.touched.subscriptionId && formik.errors.subscriptionId ? formik.errors.subscriptionId : ''}
                            />
                        </div>

                        <div className='mt-8 rowTwoInput'>
                            <DatePickerComponent
                                label={t('shop.subscription_start_date')}
                                onChange={(value) => formik.setFieldValue('subscriptionStartDate', value)}
                                placeholder={t('select')}
                                defaulValue={formik.values.subscriptionStartDate}
                                error_text={formik.touched.subscriptionStartDate && formik.errors.subscriptionStartDate ? formik.errors.subscriptionStartDate : ''}
                            />

                            <DatePickerComponent
                                label={t('shop.subscription_end_date')}
                                onChange={(value) => formik.setFieldValue('subscriptionEndDate', value)}
                                placeholder={t('select')}
                                defaulValue={formik.values.subscriptionEndDate}
                                error_text={formik.touched.subscriptionEndDate && formik.errors.subscriptionEndDate ? formik.errors.subscriptionEndDate : ''}
                            />
                        </div>

                        <div className='mt-8'>
                            <SwitchComponent
                                label={t('shop.status')}
                                active={formik.values.isActive || false}
                                onChange={(value) => formik.setFieldValue('isActive', value)}
                            />
                        </div>
                    </div>
                </div>
            </div>
        </div>
    )
}

export default UpdateShop
