import { useFormik } from 'formik'
import { type FC } from 'react'
import { CreateResellerType } from './types/Types'
import * as Yup from 'yup'
import Button from '../../components/Button'
import { TickCircle } from 'iconsax-react'
import { useTranslation } from 'react-i18next'
import { useCreateResellers } from './hooks/useResellerData'
import { useNavigate } from 'react-router-dom'
import { ErrorType } from '../../helpers/types'
import { toast } from '../../components/Toast';
import Input from '../../components/Input'

const CreateReseller: FC = () => {

    const { t } = useTranslation('global')
    const navigate = useNavigate()
    const create = useCreateResellers()

    const formik = useFormik<CreateResellerType>({
        initialValues: {
            name: '',
            phone: ''
        },
        validationSchema: Yup.object({
            name: Yup.string().required(t('errors.required')),
            phone: Yup.string().required(t('errors.required')),
        }),
        onSubmit: (values) => {
            create.mutate(values, {
                onSuccess: () => {
                    navigate(-1)
                },
                onError: (error: ErrorType) => {
                    toast(error.response?.data?.error?.message[0], 'error')
                }
            })
        }
    })

    return (
        <div className='mt-4'>
            <div className='flex justify-between items-center'>
                <div>
                    {t('discount.new_discount')}
                </div>
                <Button
                    className='w-[172px]'
                    onClick={() => formik.handleSubmit()}
                    isLoading={create.isPending}
                >
                    <div className='flex gap-2 items-center'>
                        <TickCircle size={20} color='white' />
                        <div>
                            {t('reseller.submit')}
                        </div>
                    </div>
                </Button>
            </div>

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

export default CreateReseller