import {
  Control,
  FieldErrors,
  useForm,
  UseFormRegister,
  UseFormReset,
  UseFormSetValue,
  UseFormWatch,
} from "react-hook-form";

import { useEffect, useMemo, useState } from "react";
import {
  CreateVisionPayload,
  VisionFormData,
  VisionItem,
} from "../types/visionType";
import { useVision } from "../hooks/useVision";
import { useNavigate, useParams } from "react-router-dom";
import { toast } from "sonner";
import VisionForm from "./Form";

export interface FormProps {
  watch: UseFormWatch<VisionFormData>;
  control: Control<VisionFormData>;
  setValue: UseFormSetValue<VisionFormData>;
  register: UseFormRegister<VisionFormData>;
  errors: FieldErrors<VisionFormData>;
  reset?: UseFormReset<VisionFormData>;
  handleSubmit: (e: React.FormEvent) => void;
  handleCancel: () => void;
  isSubmitting: boolean;
  item?: VisionItem;
  label: string;
}
export const EditVision = () => {
  const { id } = useParams();
  const { singleItem: item, updateItem } = useVision(undefined, id);
  const [isSubmitting, setIsSubmitting] = useState<boolean>(false);
  const navigate = useNavigate();
  const defaultValues = useMemo(
    () => ({
      visionTitleEn: item?.visionTitle?.en,
      visionTitleAm: item?.visionTitle?.am,
      visionDescriptionAm: item?.visionDescription?.am,
      visionDescriptionEn: item?.visionDescription?.en,
      isActive: item?.isActive,
    }),
    [item] // 👈 recompute only when item changes
  );
  const {
    register,
    handleSubmit,
    watch,
    control,
    reset,
    setValue,
    formState: { errors },
  } = useForm<VisionFormData>({
    defaultValues,
  });
  useEffect(() => {
    if (item) {
      reset(defaultValues);
    }
  }, [item, defaultValues, reset]);
  const handleEditSubmit = async (VisionFormData: VisionFormData) => {
    if (!item) return;
    setIsSubmitting(true);
    try {
      const payload: CreateVisionPayload = {
        visionTitle: {
          am: VisionFormData.visionTitleAm || "",
          en: VisionFormData.visionTitleEn || "",
        },
        visionDescription: {
          am: VisionFormData.visionDescriptionEn || "",
          en: VisionFormData.visionDescriptionEn || "",
        },
        isActive: VisionFormData.isActive,
      };

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