import {DialogTitle} from "@headlessui/react";
import Toggle from "@/components/ui/Toggle";
import {FC, useEffect, useState} from "react";
import {generateSchedule} from "@/utils/api/scheduleApi";
import Alert from "@/components/ui/Alert";
import SolidButton from "@/components/ui/Buttons/SolidButton";

interface ScheduleRegenerateFormProps {
    closeModal: () => void;
}

const ScheduleRegenerateForm: FC<ScheduleRegenerateFormProps> = ({closeModal}) => {
    const [overwrite, setOverwrite] = useState(false);
    const [error, setError] = useState("");

    useEffect(() => {
    }, [overwrite]);

    const close = () => {
        closeModal();
    }

    const handleToggle = () => {
        setOverwrite(!overwrite)
    }

    const handleSubmit = () => {
        generateSchedule(overwrite)
            .then(() => close())
            .catch((err) => setError(err))
    }

    return <>
        <div className="bg-gray-500 px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
            <div className="sm:flex sm:items-start w-full">
                <div className="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left ">
                    <DialogTitle as="h3" className="text-base font-semibold text-accent-blue">
                        Regenerate Schedule
                    </DialogTitle>
                    <div className="mt-5">
                        <div className="flex">
                            {
                                error && <Alert type="error">{ error }</Alert>
                            }
                            <div className="flex-1/2 pr-5">
                                <label htmlFor="overwrite" className="text-accent-blue">Overwrite current schedule</label>
                            </div>
                            <div className="flex-1/2">
                                <Toggle onChange={handleToggle} checked={overwrite} />
                            </div>
                        </div>
                    </div>


                </div>
            </div>
        </div>
        <div className="bg-gray-500 px-4 py-3 sm:flex sm:flex-row-reverse sm:px-6">
            <SolidButton
                type="button"
                onClick={() => handleSubmit()}
                className="inline-flex w-full justify-center rounded-md px-3 py-2 text-sm font-semibold shadow-xs sm:ml-3 sm:w-auto"
            >
                Regenerate
            </SolidButton>
            <SolidButton
                type="button"
                data-autofocus
                onClick={() => close()}
                className="mt-3 inline-flex w-full justify-center rounded-md bg-gray-500 px-3 py-2 text-sm font-semibold text-gray-900 ring-1 shadow-xs border-secondary ring-inset  sm:mt-0 sm:w-auto"
            >
                Cancel
            </SolidButton>
        </div>
    </>;
};

export default ScheduleRegenerateForm;