import { useForm } from "react-hook-form";
import { CreateModulesPayload, ModulesFormData } from "../types/modulesType";
import { toast } from "sonner";
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { useModules } from "../hooks/useModules";
import ModulesForm from "./Form";

export const AddModules = () => {
  const {
    register,
    handleSubmit,
    formState: { errors },
    watch,
    control,
    setValue,
  } = useForm<ModulesFormData>({
    defaultValues: {
      labelAm: "",
      labelEn: "",
      descriptionEn: "",
      descriptionAm: "",
      link: "",
      isActive: false,
    },
  });
  const navigate = useNavigate();
  const { createItem, isCreating } = useModules();
  const [isSubmitting, setIsSubmitting] = useState(false);

  const handleCreateSubmit = async (ModulesFormData: ModulesFormData) => {
    setIsSubmitting(true);
    try {
      const payload: CreateModulesPayload = {
        label: {
          am: ModulesFormData.labelAm || "",
          en: ModulesFormData.labelEn || "",
        },
        description: {
          am: ModulesFormData.descriptionAm || "",
          en: ModulesFormData.descriptionEn || "",
        },
        link: ModulesFormData.link,
        isActive: ModulesFormData.isActive,
      };
      await createItem({
        data: payload,
      });
      toast.success(" created successfully");
      navigate(-1);
    } catch (error) {
      toast.error("Failed to create Modules");
      console.error("Creation error:", error);
      setIsSubmitting(false);
    } finally {
      setIsSubmitting(false);
    }
  };
  const onCancel = () => {
    navigate(-1);
  };
  return (
    <ModulesForm
      handleSubmit={handleSubmit(handleCreateSubmit)}
      handleCancel={onCancel}
      watch={watch}
      setValue={setValue}
      control={control}
      register={register}
      errors={errors}
      isSubmitting={isSubmitting}
      label="Add Module"
    />
  );
};
