import { type FC, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
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 { useGetSchedule, useUpdateSchedule } 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 PageLoading from '@/components/PageLoading';
import { formatTimeToHHmm } from '@/helpers/utils';

const UpdateSchedule: FC = () => {
    const { id } = useParams<{ id: string }>();
    const navigate = useNavigate();
    const { data: scheduleData, isLoading } = useGetSchedule(id || '');
    const { mutate: updateSchedule, isPending } = useUpdateSchedule();

    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(),
        }),
        enableReinitialize: true,
        onSubmit: (values) => {
            if (!id) return;
            updateSchedule(
                { id, params: values },
                {
                    onSuccess: () => {
                        toast.success('زمانبندی با موفقیت ویرایش شد');
                        navigate(Pages.schedule.list);
                    },
                    onError: (error: ErrorType) => {
                        toast.error(extractErrorMessage(error));
                    },
                }
            );
        },
    });

    useEffect(() => {
        if (scheduleData?.data) {
            const schedule = scheduleData.data;
            formik.setValues({
                weekDay: schedule.weekDay,
                openTime: formatTimeToHHmm(schedule.openTime),
                closeTime: formatTimeToHHmm(schedule.closeTime),
                isActive: schedule.isActive,
            });
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [scheduleData]);

    if (isLoading) {
        return <PageLoading />;
    }

    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 UpdateSchedule;