"use client";

import { useFormState } from "react-dom";
import { useEffect, useState } from "react";
import { toast } from "react-toastify";
import { generateTimetableLessons } from "@/lib/actions";

const GenerateTimetableForm = ({ termId, schoolId }: { termId: number; schoolId: string }) => {
    const [state, formAction] = useFormState(generateTimetableLessons, {
        success: false,
        error: false,
        message: "",
    });

    const [isGenerating, setIsGenerating] = useState(false);

    useEffect(() => {
        if (state.success) {
            toast.success(state.message || "Timetable generated successfully!");
            setIsGenerating(false);
        } else if (state.error) {
            toast.error(state.message || "Failed to generate timetable.");
            setIsGenerating(false);
        }
    }, [state]);

    const handleSubmit = (formData: FormData) => {
        setIsGenerating(true);
        formAction(formData);
    };

    return (
        <form action={handleSubmit}>
            <input type="hidden" name="termId" value={termId} />
            <input type="hidden" name="schoolId" value={schoolId} />
            <button
                disabled={isGenerating}
                className="bg-lamaSky text-white px-3 py-1 text-sm rounded-md disabled:opacity-50 hover:bg-lamaSkyLight"
            >
                {isGenerating ? "Generating..." : "Generate Timetable"}
            </button>
        </form>
    );
};

export default GenerateTimetableForm;
