import {
  Control,
  FieldErrors,
  useForm,
  UseFormRegister,
  UseFormReset,
  UseFormSetValue,
  UseFormWatch,
} from "react-hook-form";
import {
  ContactUsFormData,
  ContactUsItem,
  CreateContactUsPayload,
} from "../types/contactUs";
import { useContactUs } from "../hooks/useContactUs";
import { useNavigate, useParams } from "react-router-dom";
import { toast } from "sonner";
import { useEffect, useMemo, useState } from "react";
import ContactUsForm from "./Form";

export interface FormProps {
  watch: UseFormWatch<ContactUsFormData>;
  control: Control<ContactUsFormData>;
  setValue: UseFormSetValue<ContactUsFormData>;
  register: UseFormRegister<ContactUsFormData>;
  errors: FieldErrors<ContactUsFormData>;
  reset?: UseFormReset<ContactUsFormData>;
  handleSubmit: (e: React.FormEvent) => void;
  handleCancel: () => void;
  isSubmitting: boolean;
  item?: ContactUsItem;
  label: string;
}
export const EditContactUs = () => {
  const { id } = useParams();
  const { singleItem: item, updateItem } = useContactUs(undefined, id);
  const [isSubmitting, setIsSubmitting] = useState<boolean>(false);
  const navigate = useNavigate();
  const defaultValues = useMemo(
    () => ({
      nameEn: item?.name?.en,
      nameAm: item?.name?.am,
      value: item?.value,
      type: item?.type,
      isActive: item?.isActive,
    }),
    [item] // 👈 recompute only when item changes
  );

  const {
    register,
    handleSubmit,
    watch,
    reset,
    control,
    setValue,
    formState: { errors },
  } = useForm<ContactUsFormData>({
    defaultValues,
  });
  useEffect(() => {
    if (item) {
      reset(defaultValues);
    }
  }, [item, defaultValues, reset]);
  const handleEditSubmit = async (ContactUsFormData: ContactUsFormData) => {
    if (!item) return;
    setIsSubmitting(true);
    try {
      const payload: CreateContactUsPayload = {
        name: {
          am: ContactUsFormData.nameAm || "",
          en: ContactUsFormData.nameEn || "",
        },
        type: ContactUsFormData.type,
        value: ContactUsFormData.value,

        isActive: ContactUsFormData.isActive,
      };

      await updateItem({
        id: item?.id,
        data: payload,
      });
      toast.success("ContactUs 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 (
    <ContactUsForm
      handleSubmit={handleSubmit(handleEditSubmit)}
      handleCancel={onCancel}
      watch={watch}
      setValue={setValue}
      control={control}
      register={register}
      errors={errors}
      isSubmitting={isSubmitting}
      label="Edit Contact Information"
    />
  );
};
