import { FC, useState } from 'react'
import Button from '../../../components/Button'
import { Add, AddCircle, TickCircle, Trash } from 'iconsax-react'
import { useTranslation } from 'react-i18next'
import DefaulModal from '../../../components/DefaulModal'
import Input from '../../../components/Input'
import { useFormik } from 'formik'
import { CreateItemPlanType, CreatePlanType } from '../types/ServiceTypes'
import * as Yup from 'yup'
import { clx } from '../../../helpers/utils'
import { toast } from 'react-toastify'
import { useCreatePlan, useGetPlans } from '../hooks/useServiceData'
import { useParams } from 'react-router-dom'
import { ErrorType } from '../../../helpers/types'

const CreatePlan: FC = () => {

    const { id } = useParams()
    const { t } = useTranslation('global')
    const [showModal, setShowModal] = useState<boolean>(false)
    const [items, setItems] = useState<CreateItemPlanType[]>([])
    const getPlans = useGetPlans(id)
    const createPlan = useCreatePlan()

    const formik = useFormik<CreateItemPlanType>({
        initialValues: {
            name: '',
            duration: '',
            isActive: true,
            price: ''
        },
        validationSchema: Yup.object({
            name: Yup.string()
                .required(t('errors.required')),
            duration: Yup.string()
                .required(t('errors.required')),
            price: Yup.string()
                .required(t('errors.required')),
        }),
        onSubmit: (values) => {
            const vals = {
                ...values,
                duration: +values.duration,
                price: +values.price,
            }
            setItems([...items, vals])
            formik.resetForm()
        }
    })

    const handleDeleteItem = (index: number) => {
        const newItems = items.filter((_, i) => i !== index)
        setItems(newItems)
    }

    const handleSubmit = () => {
        if (items.length === 0) {
            toast.error(t('plan.error_submit'))
        } else {
            const params: CreatePlanType = {
                serviceId: id ? id : '',
                subs: items
            }

            createPlan.mutate(params, {
                onSuccess: () => {
                    formik.resetForm()
                    setShowModal(false)
                    toast.success(t('plan.success_submit'))
                },
                onError: (error: ErrorType) => {
                    toast.error(error.response?.data?.error?.message[0])
                }
            })
        }
    }

    return (
        <div>
            <Button
                className='px-5'
                onClick={() => setShowModal(true)}
            >
                <div className='flex gap-2'>
                    <Add
                        className='size-5'
                        color='#fff'
                    />
                    <div>{t('plan.new_plan')}</div>
                </div>
            </Button>

            <DefaulModal
                open={showModal}
                close={() => setShowModal(false)}
                title_header={t('plan.add_plan') + ' ' + getPlans.data?.data?.service?.name}
                isHeader
            >
                <div className='mt-6'>
                    {
                        items.map((item, index: number) => {
                            return (
                                <div className='flex justify-between items-center gap-8 mt-4'>
                                    <Input
                                        className='bg-description bg-opacity-15 border-none'
                                        value={item.name}
                                        readOnly
                                    />
                                    <Input
                                        className='bg-description bg-opacity-15 border-none'
                                        value={item.duration}
                                        readOnly
                                    />
                                    <Input
                                        className='bg-description bg-opacity-15 border-none'
                                        value={item.price}
                                        readOnly
                                        seprator
                                    />

                                    <Trash
                                        size={24}
                                        color='#D52903'
                                        className='min-w-6'
                                        onClick={() => handleDeleteItem(index)}
                                    />
                                </div>
                            )
                        })
                    }
                    <div className={clx(
                        'flex justify-between items-start gap-8',
                        items.length > 0 && 'mt-8',
                    )}>
                        <Input
                            label={t('title')}
                            className='bg-white bg-opacity-30'
                            name='name'
                            value={formik.values.name}
                            onChange={formik.handleChange}
                            error_text={formik.touched.name && formik.errors.name ? formik.errors.name : ''}
                        />
                        <Input
                            label={t('plan.time')}
                            className='bg-white bg-opacity-30'
                            name='duration'
                            value={formik.values.duration}
                            onChange={formik.handleChange}
                            error_text={formik.touched.duration && formik.errors.duration ? formik.errors.duration : ''}
                        />
                        <Input
                            label={t('plan.price')}
                            className='bg-white bg-opacity-30'
                            name='price'
                            value={formik.values.price}
                            onChange={(e) => formik.setFieldValue('price', e.target.value)}
                            error_text={formik.touched.price && formik.errors.price ? formik.errors.price : ''}
                            seprator
                        />

                        <div onClick={() => formik.handleSubmit()} className='size-10 min-w-10 mt-7 rounded-xl border border-black flex justify-center items-center'>
                            <AddCircle size={20} color='black' />
                        </div>
                    </div>

                    <div className='mt-12 border-t border-border pt-5 flex justify-end'>
                        <div className='flex gap-5 items-center'>
                            <Button
                                className='w-[150px] bg-white bg-opacity-15 text-description'
                                label={t('plan.cancel')}
                                onClick={() => setShowModal(false)}
                            />

                            <Button
                                onClick={handleSubmit}
                            >
                                <div className='flex gap-2'>
                                    <TickCircle
                                        size={20}
                                        color='white'
                                    />
                                    <div>
                                        {t('plan.submit_plan')}
                                    </div>
                                </div>
                            </Button>
                        </div>
                    </div>
                </div>

            </DefaulModal>
        </div>
    )
}

export default CreatePlan