"use client";

import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import InputField from "../InputField";
import { timetableEntrySchema, TimetableEntrySchema } from "@/lib/formValidationSchemas";
import { createTimetableEntry, updateTimetableEntry } from "@/lib/actions";
import { useFormState } from "react-dom";
import { Dispatch, SetStateAction, useEffect } from "react";
import { toast } from "react-toastify";
import { useRouter } from "next/navigation";
import { useUser } from "@clerk/nextjs";

const TimetableEntryForm = ({
    type,
    data,
    setOpen,
    relatedData,
}: {
    type: "create" | "update";
    data?: any;
    setOpen: Dispatch<SetStateAction<boolean>>;
    relatedData?: any;
}) => {
    const { user } = useUser();
    const schoolId = user?.publicMetadata?.schoolId as string;

    const {
        register,
        handleSubmit,
        formState: { errors },
    } = useForm<TimetableEntrySchema>({
        resolver: zodResolver(timetableEntrySchema),
    });

    const [state, formAction] = useFormState(
        type === "create" ? createTimetableEntry : updateTimetableEntry,
        {
            success: false,
            error: false,
        }
    );

    const onSubmit = handleSubmit((formData) => {
        formAction(formData);
    });

    const router = useRouter();

    useEffect(() => {
        if (state.success) {
            toast(`Timetable Entry has been ${type === "create" ? "created" : "updated"}!`);
            setOpen(false);
            router.refresh();
        }
    }, [state, router, type, setOpen]);

    // relatedData structure: { classes, subjects, slots }
    const { classes, subjects, slots } = relatedData || { classes: [], subjects: [], slots: [] };

    return (
        <form className="flex flex-col gap-8" onSubmit={onSubmit}>
            <h1 className="text-xl font-semibold">
                {type === "create" ? "Create a new entry" : "Update the entry"}
            </h1>

            <div className="flex justify-between flex-wrap gap-4">

                {/* Template ID passed by the Template UI, either via prop or query string.
            If data has timetableTemplateId, we default it and hide/disable it if needed,
            or let the user select it if they are managing globally. For this view, 
            it's expected we'll inject it via data.
         */}
                <div className="flex flex-col gap-2 w-full md:w-1/4">
                    <label className="text-xs text-gray-500">Template ID</label>
                    <input
                        className="ring-[1.5px] ring-gray-300 p-2 rounded-md text-sm w-full"
                        {...register("timetableTemplateId")}
                        defaultValue={data?.teacherTimetableTemplateId ?? data?.timetableTemplateId}
                        readOnly={!!data?.timetableTemplateId}
                    />
                    {errors.timetableTemplateId?.message && (
                        <p className="text-xs text-red-400">
                            {errors.timetableTemplateId.message.toString()}
                        </p>
                    )}
                </div>

                <div className="flex flex-col gap-2 w-full md:w-1/4">
                    <label className="text-xs text-gray-500">Day of Week</label>
                    <select
                        className="ring-[1.5px] ring-gray-300 p-2 rounded-md text-sm w-full"
                        {...register("dayOfWeek")}
                        defaultValue={data?.dayOfWeek}
                    >
                        <option value="1">Monday</option>
                        <option value="2">Tuesday</option>
                        <option value="3">Wednesday</option>
                        <option value="4">Thursday</option>
                        <option value="5">Friday</option>
                        <option value="6">Saturday</option>
                        <option value="7">Sunday</option>
                    </select>
                    {errors.dayOfWeek?.message && (
                        <p className="text-xs text-red-400">
                            {errors.dayOfWeek.message.toString()}
                        </p>
                    )}
                </div>

                <div className="flex flex-col gap-2 w-full md:w-1/4">
                    <label className="text-xs text-gray-500">Time Slot</label>
                    <select
                        className="ring-[1.5px] ring-gray-300 p-2 rounded-md text-sm w-full"
                        {...register("schoolTimetableSlotId")}
                        defaultValue={data?.schoolTimetableSlotId}
                    >
                        {slots.map((slot: any) => (
                            <option value={slot.id} key={slot.id}>
                                {slot.name} ({slot.startTime} - {slot.endTime})
                            </option>
                        ))}
                    </select>
                    {errors.schoolTimetableSlotId?.message && (
                        <p className="text-xs text-red-400">
                            {errors.schoolTimetableSlotId.message.toString()}
                        </p>
                    )}
                </div>

                <div className="flex flex-col gap-2 w-full md:w-1/4">
                    <label className="text-xs text-gray-500">Class</label>
                    <select
                        className="ring-[1.5px] ring-gray-300 p-2 rounded-md text-sm w-full"
                        {...register("classId")}
                        defaultValue={data?.classId}
                    >
                        {classes.map((c: any) => (
                            <option value={c.id} key={c.id}>
                                {c.name}
                            </option>
                        ))}
                    </select>
                    {errors.classId?.message && (
                        <p className="text-xs text-red-400">
                            {errors.classId.message.toString()}
                        </p>
                    )}
                </div>

                <div className="flex flex-col gap-2 w-full md:w-1/4">
                    <label className="text-xs text-gray-500">Subject</label>
                    <select
                        className="ring-[1.5px] ring-gray-300 p-2 rounded-md text-sm w-full"
                        {...register("subjectId")}
                        defaultValue={data?.subjectId}
                    >
                        {subjects.map((s: any) => (
                            <option value={s.id} key={s.id}>
                                {s.name}
                            </option>
                        ))}
                    </select>
                    {errors.subjectId?.message && (
                        <p className="text-xs text-red-400">
                            {errors.subjectId.message.toString()}
                        </p>
                    )}
                </div>

                {data?.id && (
                    <InputField
                        label="Id"
                        name="id"
                        defaultValue={data.id}
                        register={register}
                        error={errors?.id}
                        hidden
                    />
                )}

            </div>

            {state.error && (
                <span className="text-red-500">Something went wrong!</span>
            )}
            <button className="bg-blue-400 text-white p-2 rounded-md">
                {type === "create" ? "Create" : "Update"}
            </button>
        </form>
    );
};

export default TimetableEntryForm;
