"use client";

import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import InputField from "../InputField";
import { schoolTimetableSlotSchema, SchoolTimetableSlotSchema } from "@/lib/formValidationSchemas";
import { createSchoolTimetableSlot, updateSchoolTimetableSlot } 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 SchoolTimetableSlotForm = ({
    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<SchoolTimetableSlotSchema>({
        resolver: zodResolver(schoolTimetableSlotSchema),
    });

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

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

    const router = useRouter();

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

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

            <div className="flex justify-between flex-wrap gap-4">
                <InputField
                    label="Slot Name (e.g., Period 1, Registration)"
                    name="name"
                    defaultValue={data?.name}
                    register={register}
                    error={errors?.name}
                />
                <InputField
                    label="Start Time (e.g., 08:00)"
                    name="startTime"
                    type="time"
                    defaultValue={data?.startTime}
                    register={register}
                    error={errors?.startTime}
                />
                <InputField
                    label="End Time  (e.g., 09:00)"
                    name="endTime"
                    type="time"
                    defaultValue={data?.endTime}
                    register={register}
                    error={errors?.endTime}
                />

                <div className="flex flex-col gap-2 w-full md:w-1/4 justify-center">
                    <div className="flex items-center gap-2 mt-4">
                        <input
                            type="checkbox"
                            id="isTeachingSlot"
                            {...register("isTeachingSlot")}
                            defaultChecked={data?.isTeachingSlot ?? true}
                            className="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500"
                        />
                        <label htmlFor="isTeachingSlot" className="text-sm text-gray-700">
                            Is a Teaching Slot?
                        </label>
                    </div>
                    {errors.isTeachingSlot?.message && (
                        <p className="text-xs text-red-400">
                            {errors.isTeachingSlot.message.toString()}
                        </p>
                    )}
                </div>

                {data && (
                    <InputField
                        label="Id"
                        name="id"
                        defaultValue={data?.id}
                        register={register}
                        error={errors?.id}
                        hidden
                    />
                )}
                <input type="hidden" value={schoolId || ""} {...register("schoolId")} />
            </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 SchoolTimetableSlotForm;
