import { useForm } from "react-hook-form";
import { CreateGoalPayload, GoalFormData } from "../types/goalType";
import { toast } from "sonner";
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { useGoal } from "../hooks/useGoal";
import GoalForm from "./Form";

export const AddGoal = () => {
  const {
    register,
    handleSubmit,
    formState: { errors },
    watch,
    control,
    setValue,
  } = useForm<GoalFormData>({
    defaultValues: {
      GoalTitleEn: "",
      GoalTitleAm: "",
      GoalDescriptionAm: "",
      GoalDescriptionEn: "",
      isActive: false,
    },
  });
  const navigate = useNavigate();
  const { createItem, isCreating } = useGoal();
  const [isSubmitting, setIsSubmitting] = useState(false);

  const handleCreateSubmit = async (GoalFormData: GoalFormData) => {
    setIsSubmitting(true);
    try {
      const imageFile = GoalFormData.image?.[0];
      if (!imageFile) {
        throw new Error("images are required");
      }
      const payload: CreateGoalPayload = {
        goalTitle: {
          am: GoalFormData.GoalTitleAm || "",
          en: GoalFormData.GoalTitleEn || "",
        },
        goalDescription: {
          am: GoalFormData.GoalDescriptionEn || "",
          en: GoalFormData.GoalDescriptionEn || "",
        },
        fileInfo: {
          fileName: imageFile.name,
          contentType: imageFile.type,
          size: imageFile.size,
          originalname: imageFile.name,
        },
        isActive: GoalFormData.isActive,
      };
      await createItem({
        data: payload,
        imageFile: imageFile,
      });
      toast.success(" created successfully");
      navigate(-1);
    } catch (error) {
      toast.error("Failed to create Goal");
      console.error("Creation error:", error);
      setIsSubmitting(false);
    } finally {
      setIsSubmitting(false);
    }
  };
  const onCancel = () => {
    navigate(-1);
  };
  return (
    <GoalForm
      handleSubmit={handleSubmit(handleCreateSubmit)}
      handleCancel={onCancel}
      watch={watch}
      setValue={setValue}
      control={control}
      register={register}
      errors={errors}
      isSubmitting={isSubmitting}
      label="Add Goal"
    />
  );
};
