"use client";
import { Modal } from "flowbite-react";
import { FC, useRef, useState } from "react";
import { FormProvider, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { toast } from "react-toastify";
import { InputField } from "../forms/Inputs";
import { z } from "zod";
import ActionButton from "../action-button";
import getData, { postData, putData } from "@/utils/fetch";
import { useParseError } from "@/utils/lib/helpers";

const departmentSchema = z.object({
    name: z.string().min(1, "Name is required"),
});

type TSdepartmentSchema = z.infer<typeof departmentSchema>;

interface Props {
    isOpen: boolean;
    setOpen: (value: boolean) => void;
    department_id?: string;
    mode?: "create" | "edit";
}

const DepartmentForm: FC<Props> = ({ isOpen, setOpen, department_id, mode = "create" }) => {
    const queryClient = useQueryClient();
    const inputRef = useRef<HTMLInputElement>(null);

    const getDepartment = async (): Promise<TSdepartmentSchema> => {
        if (mode === "edit" && isOpen) {
            const response = await getData(`/api/v1/departments/${department_id}`);
            return response?.data;
        }
        return {}
    }

    const departmentForm = useForm<TSdepartmentSchema>({
        resolver: zodResolver(departmentSchema),
        mode: "onChange",
        defaultValues: async () => getDepartment(),
    });

    const {
        handleSubmit,
        reset,
        formState: { errors },
    } = departmentForm;

    const { mutate: submitDepartment, isPending } = useMutation({
        mutationFn: async (departmentForm: TSdepartmentSchema) => {
            if (mode === "create") {
                const data = await postData(
                    `/api/v1/departments`,
                    departmentForm as any
                );
                return data;
            } else {
                const { data } = await putData(
                    `/api/v1/departments/${department_id}`,
                    departmentForm as any
                );
                return data;
            }
        },
        onSuccess: (data) => {
            queryClient.invalidateQueries({ queryKey: ["departments"] });
            toast.success("Department created successfully!");
            setOpen(false);
            reset();
        },
        onError: (error: any) => {
            toast.error(useParseError(error));
        },
    });

    const onSubmit = (data: TSdepartmentSchema) => {
        submitDepartment(data);
    };

    const onError = (data: any) => {
        console.log(data);
    };

    return (
        <Modal show={isOpen} onClose={() => setOpen(false)}>
            <Modal.Header>
                {mode === "edit" ? "Edit Department" : "Create New Department"}
            </Modal.Header>
            <Modal.Body>
                <FormProvider {...departmentForm}>
                    <form onSubmit={handleSubmit(onSubmit, onError)} className="space-y-4">
                        <div>
                            <InputField
                                name="name"
                                labelText="Name"
                                placeholder="Enter department name"
                                errors={errors}
                            />
                        </div>

                        <input className="opacity-0" type="submit" ref={inputRef} />
                    </form>
                </FormProvider>
            </Modal.Body>
            <Modal.Footer>
                <ActionButton
                    onClick={() => inputRef.current?.click()}
                    type="submit"
                    title="Save"
                    isLoading={isPending}
                />
            </Modal.Footer>
        </Modal>
    );
};

export default DepartmentForm; 