import { type FC } from 'react';
import { useFormik } from 'formik';
import * as Yup from 'yup';
import { TickCircle } from 'iconsax-react';
import { toast } from 'react-toastify';
import Button from '@/components/Button';
import ScheduleFormFields from './components/ScheduleFormFields';
import { useCreateSchedule } from './hooks/useScheduleData';
import type { CreateScheduleType } from './types/Types';
import { Pages } from '@/config/Pages';
import type { ErrorType } from '@/helpers/types';
import { extractErrorMessage } from '@/config/func';
import { useNavigate } from 'react-router-dom';

const CreateSchedule: FC = () => {
    const { mutate: createSchedule, isPending } = useCreateSchedule();
    const navigate = useNavigate();
    const formik = useFormik<CreateScheduleType>({
        initialValues: {
            weekDay: 1,
            openTime: '',
            closeTime: '',
            isActive: true,
        },
        validationSchema: Yup.object().shape({
            weekDay: Yup.number()
                .required('روز هفته الزامی است')
                .min(0, 'روز هفته باید بین 1 تا 7 باشد')
                .max(6, 'روز هفته باید بین 1 تا 7 باشد'),
            openTime: Yup.string().required('زمان شروع الزامی است'),
            closeTime: Yup.string().required('زمان پایان الزامی است'),
            isActive: Yup.boolean(),
        }),
        onSubmit: (values) => {
            createSchedule(values, {
                onSuccess: () => {
                    toast.success('زمانبندی با موفقیت ایجاد شد');
                    navigate(Pages.schedule.list);
                },
                onError: (error: ErrorType) => {
                    toast.error(extractErrorMessage(error));
                },
            });
        },
    });

    return (
        <div className='mt-5'>
            <div className='flex w-full justify-between items-center'>
                <div className='text-lg font-light'>
                    زمانبندی جدید
                </div>
                <div>
                    <Button
                        className='px-5'
                        onClick={() => formik.handleSubmit()}
                        isLoading={isPending}
                    >
                        <div className='flex gap-2 items-center'>
                            <TickCircle className='size-5' color='white' />
                            <div>ثبت زمانبندی</div>
                        </div>
                    </Button>
                </div>
            </div>

            <div className='mt-6'>
                <ScheduleFormFields formik={formik} />
            </div>
        </div>
    );
};

export default CreateSchedule;