"use client";

import { useFormState } from "react-dom";
import { useEffect, useState } from "react";
import { toast } from "react-toastify";
import { generateLessonsFromTemplate } from "@/lib/actions";
import { useRouter } from "next/navigation";

type TermOption = { id: number; name: string; startDate: string; endDate: string };

const GenerateLessonsForm = ({
    templateId,
    schoolId,
    terms,
}: {
    templateId: number;
    schoolId: string;
    terms: TermOption[];
}) => {
    const [state, formAction] = useFormState(generateLessonsFromTemplate, {
        success: false,
        error: false,
        message: "",
    });
    const [isGenerating, setIsGenerating] = useState(false);
    const [useTerm, setUseTerm] = useState(true);
    const router = useRouter();

    useEffect(() => {
        if (state.success) {
            toast.success(state.message || "Lessons generated.");
            setIsGenerating(false);
            router.refresh();
        } else if (state.error) {
            toast.error(state.message || "Failed to generate lessons.");
            setIsGenerating(false);
        }
    }, [state, router]);

    return (
        <form
            action={(fd) => {
                setIsGenerating(true);
                formAction(fd);
            }}
            className="flex flex-col gap-3 p-4 bg-slate-50 rounded-lg border border-slate-200"
        >
            <h3 className="font-semibold text-sm text-gray-700">Generate lessons for your calendar</h3>
            <p className="text-xs text-gray-500">
                This will create lessons from this template for the chosen period. Any existing lessons in that range for this teacher will be replaced.
            </p>
            <input type="hidden" name="templateId" value={templateId} />
            <input type="hidden" name="schoolId" value={schoolId} />

            <div className="flex flex-wrap gap-4 items-end">
                <label className="flex items-center gap-2">
                    <input
                        type="radio"
                        checked={useTerm}
                        onChange={() => setUseTerm(true)}
                        className="rounded"
                    />
                    <span className="text-sm">Use a term</span>
                </label>
                <label className="flex items-center gap-2">
                    <input
                        type="radio"
                        checked={!useTerm}
                        onChange={() => setUseTerm(false)}
                        className="rounded"
                    />
                    <span className="text-sm">Custom date range</span>
                </label>
            </div>

            {useTerm ? (
                <div className="flex flex-col gap-1">
                    <label className="text-xs text-gray-500">Term</label>
                    <select
                        name="termId"
                        className="ring-1 ring-gray-300 rounded px-2 py-1.5 text-sm w-full max-w-xs"
                        required={useTerm}
                    >
                        <option value="">Select term</option>
                        {terms.map((t) => (
                            <option key={t.id} value={t.id}>
                                {t.name} ({new Date(t.startDate).toLocaleDateString()} – {new Date(t.endDate).toLocaleDateString()})
                            </option>
                        ))}
                    </select>
                    <input type="hidden" name="startDate" value="" />
                    <input type="hidden" name="endDate" value="" />
                </div>
            ) : (
                <div className="flex flex-wrap gap-3 items-end">
                    <div className="flex flex-col gap-1">
                        <label className="text-xs text-gray-500">Start date</label>
                        <input
                            type="date"
                            name="startDate"
                            className="ring-1 ring-gray-300 rounded px-2 py-1.5 text-sm"
                            required={!useTerm}
                        />
                    </div>
                    <div className="flex flex-col gap-1">
                        <label className="text-xs text-gray-500">End date</label>
                        <input
                            type="date"
                            name="endDate"
                            className="ring-1 ring-gray-300 rounded px-2 py-1.5 text-sm"
                            required={!useTerm}
                        />
                    </div>
                    <input type="hidden" name="termId" value="" />
                </div>
            )}

            <button
                type="submit"
                disabled={isGenerating}
                className="bg-lamaSky text-white px-4 py-2 text-sm rounded-md disabled:opacity-50 hover:bg-lamaSkyLight w-fit"
            >
                {isGenerating ? "Generating…" : "Generate lessons"}
            </button>
        </form>
    );
};

export default GenerateLessonsForm;
