import {
  Control,
  FieldErrors,
  useForm,
  UseFormRegister,
  UseFormReset,
  UseFormSetValue,
  UseFormWatch,
} from "react-hook-form";
import { useEffect, useMemo, useState } from "react";
import { CreateGoalPayload, GoalFormData, GoalItem } from "../types/goalType";
import { toast } from "sonner";
import { useGoal } from "../hooks/useGoal";
import { useNavigate, useParams } from "react-router-dom";
import GoalForm from "./Form";

export interface FormProps {
  watch: UseFormWatch<GoalFormData>;
  control: Control<GoalFormData>;
  setValue: UseFormSetValue<GoalFormData>;
  register: UseFormRegister<GoalFormData>;
  errors: FieldErrors<GoalFormData>;
  reset?: UseFormReset<GoalFormData>;
  handleSubmit: (e: React.FormEvent) => void;
  handleCancel: () => void;
  isSubmitting: boolean;
  item?: GoalItem;
  label: string;
}
export const EditGoal = () => {
  const { id } = useParams();
  const { updateItem, singleItem: item } = useGoal(undefined, id);
  const [editingItem, setEditingItem] = useState<boolean>(false);
  const navigate = useNavigate();
  const defaultValues = useMemo(
    () => ({
      GoalTitleEn: item?.goalTitle.en,
      GoalTitleAm: item?.goalTitle.am,
      GoalDescriptionAm: item?.goalDescription.am,
      GoalDescriptionEn: item?.goalDescription.en,
      isActive: item?.isActive,
      image: undefined,
    }),
    [item] // 👈 recompute only when item changes
  );
  const {
    register,
    handleSubmit,
    watch,
    control,
    setValue,
    reset,
    formState: { errors },
  } = useForm<GoalFormData>({
    defaultValues,
  });
  useEffect(() => {
    if (item) {
      reset(defaultValues);
    }
  }, [item, defaultValues, reset]);
  const handleEditSubmit = async (GoalFormData: GoalFormData) => {
    if (!item) return;
    setEditingItem(true);
    try {
      const imageFile = GoalFormData.image?.[0];
      const payload: CreateGoalPayload = {
        goalTitle: {
          am: GoalFormData.GoalTitleAm || "",
          en: GoalFormData.GoalTitleEn || "",
        },
        goalDescription: {
          am: GoalFormData.GoalDescriptionEn || "",
          en: GoalFormData.GoalDescriptionEn || "",
        },
        fileInfo: imageFile
          ? {
              fileName: imageFile.name,
              contentType: imageFile.type,
              size: imageFile.size,
              originalname: imageFile.name,
            }
          : undefined,
        isActive: GoalFormData.isActive,
      };

      await updateItem({
        id: item?.id || "",
        data: payload,
        ...(imageFile && { imageFile }),
      });
      toast.success("Goal updated successfully");
      navigate(-1);
    } catch (error) {
      toast.error("Failed to update about us");
      console.error("Update error:", error);
      setEditingItem(false);
    }
  };
  const onCancel = () => {
    navigate(-1);
  };
  return (
    <GoalForm
      handleSubmit={handleSubmit(handleEditSubmit)}
      handleCancel={onCancel}
      watch={watch}
      setValue={setValue}
      control={control}
      register={register}
      errors={errors}
      isSubmitting={editingItem}
      label="Edit Goal"
      item={item}
    />
  );
};
