import { FC } from 'react'
import { useTranslation } from 'react-i18next'
import Input from '../../../components/Input'
import Button from '../../../components/Button'
import { TickCircle } from 'iconsax-react'
import * as Yup from 'yup'
import { useFormik } from 'formik'
import { toast } from '../../../components/Toast';
import { ErrorType } from '../../../helpers/types'
import { CreateCategoryLearningType } from '../types/LearningTypes'
import { useCreateCategory, useGetCategory } from '../hooks/useLearningData'

const CreateCategory: FC = () => {

    const { t } = useTranslation('global')
    const createCategory = useCreateCategory()
    const getCategory = useGetCategory()

    const formik = useFormik<CreateCategoryLearningType>({
        initialValues: {
            name: ''
        },
        validationSchema: Yup.object({
            name: Yup.string().required(t('errors.required')),
        }),
        onSubmit: (values) => {

            createCategory.mutate(values, {
                onSuccess: () => {
                    formik.resetForm()
                    getCategory.refetch()
                    toast(t('success'), 'success')
                },
                onError: (error: ErrorType) => {
                    toast(error?.response?.data?.error?.message[0], 'error')
                }
            })
        }
    })

    return (
        <div className='bg-white p-8 w-sidebar hidden xl:block rounded-3xl overflow-hidden relative'>
            <div>
                {t('service.add_category')}
            </div>


            <div className='mt-8'>
                <Input
                    label={t('service.title_category')}
                    value={formik.values.name}
                    name='name'
                    onChange={formik.handleChange}
                    error_text={formik.touched.name && formik.errors.name ? formik.errors.name : ''}
                />
            </div>





            <div className='flex flex-1 justify-end items-end mt-8'>
                <Button
                    className='w-fit px-5'
                    onClick={() => formik.handleSubmit()}
                    isLoading={createCategory.isPending}
                >
                    <div className='flex items-center gap-2'>
                        <TickCircle
                            className='size-5'
                            color='white'
                        />
                        <div>{t('save')}</div>
                    </div>
                </Button>
            </div>
        </div>
    )
}

export default CreateCategory