import {
  Control,
  FieldErrors,
  useForm,
  UseFormRegister,
  UseFormReset,
  UseFormSetValue,
  UseFormWatch,
} from "react-hook-form";
import {
  CreateModulesPayload,
  ModulesFormData,
  ModulesItem,
} from "../types/modulesType";
import { useModules } from "../hooks/useModules";
import { useNavigate, useParams } from "react-router-dom";
import { toast } from "sonner";
import { useEffect, useMemo, useState } from "react";
import ModulesForm from "./Form";

export interface FormProps {
  watch: UseFormWatch<ModulesFormData>;
  control: Control<ModulesFormData>;
  setValue: UseFormSetValue<ModulesFormData>;
  register: UseFormRegister<ModulesFormData>;
  errors: FieldErrors<ModulesFormData>;
  reset?: UseFormReset<ModulesFormData>;
  handleSubmit: (e: React.FormEvent) => void;
  handleCancel: () => void;
  isSubmitting: boolean;
  item?: ModulesItem;
  label: string;
}
export const EditModules = () => {
  const { id } = useParams();
  const { singleItem: item, updateItem } = useModules(undefined, id);
  const [isSubmitting, setIsSubmitting] = useState<boolean>(false);
  const navigate = useNavigate();
  const defaultValues = useMemo(
    () => ({
      labelAm: item?.label.am,
      labelEn: item?.label.en,
      descriptionEn: item?.description.en,
      descriptionAm: item?.description.am,
      link: item?.link,
      isActive: item?.isActive,
    }),
    [item] // 👈 recompute only when item changes
  );
  const {
    register,
    handleSubmit,
    watch,
    control,
    reset,
    setValue,
    formState: { errors },
  } = useForm<ModulesFormData>({
    defaultValues,
  });
  useEffect(() => {
    if (item) {
      reset(defaultValues);
    }
  }, [item, defaultValues, reset]);
  const handleEditSubmit = async (ModulesFormData: ModulesFormData) => {
    if (!item) return;
    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 updateItem({
        id: item?.id,
        data: payload,
      });
      toast.success("Modules 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 (
    <ModulesForm
      handleSubmit={handleSubmit(handleEditSubmit)}
      handleCancel={onCancel}
      watch={watch}
      setValue={setValue}
      control={control}
      register={register}
      errors={errors}
      isSubmitting={isSubmitting}
      label="Edit Module"
    />
  );
};
