import {
  Control,
  FieldErrors,
  useForm,
  UseFormRegister,
  UseFormReset,
  UseFormSetValue,
  UseFormWatch,
} from "react-hook-form";
import { useEffect, useMemo, useState } from "react";
import {
  CreateNewsCategoryPayload,
  NewsCategoryFormData,
  NewsCategoryItem,
} from "../types/newsCategoryType";
import { useNewsCategory } from "../hooks/useNewsCategory";
import { useNavigate, useParams } from "react-router-dom";
import { toast } from "sonner";
import NewsCategoryForm from "./Form";

export interface FormProps {
  watch: UseFormWatch<NewsCategoryFormData>;
  control: Control<NewsCategoryFormData>;
  setValue: UseFormSetValue<NewsCategoryFormData>;
  register: UseFormRegister<NewsCategoryFormData>;
  errors: FieldErrors<NewsCategoryFormData>;
  reset?: UseFormReset<NewsCategoryFormData>;
  handleSubmit: (e: React.FormEvent) => void;
  handleCancel: () => void;
  isSubmitting: boolean;
  item?: NewsCategoryItem;
  label: string;
}
export const EditNewsCategory = () => {
  const { id } = useParams();
  const { singleItem: item, updateItem } = useNewsCategory(undefined, id);
  const [isSubmitting, setIsSubmitting] = useState<boolean>(false);
  const navigate = useNavigate();
  const defaultValues = useMemo(
    () => ({
      NewsCategoryTitleEn: item?.newsCategoryTitle?.en || "",
      NewsCategoryTitleAm: item?.newsCategoryTitle?.am || "",
      NewsCategoryDescriptionAm: item?.newsCategoryDescription?.am || "",
      NewsCategoryDescriptionEn: item?.newsCategoryDescription?.en || "",
      color: item?.color || "#007BFF",
      isActive: item?.isActive || false,
      image: undefined,
    }),
    [item] // 👈 recompute only when item changes
  );
  const {
    register,
    handleSubmit,
    watch,
    control,
    reset,
    setValue,
    formState: { errors },
  } = useForm<NewsCategoryFormData>({
    defaultValues,
  });
  useEffect(() => {
    if (item) {
      reset(defaultValues);
    }
  }, [item, defaultValues, reset]);

  const handleEditSubmit = async (
    NewsCategoryFormData: NewsCategoryFormData
  ) => {
    if (!item) return;
    setIsSubmitting(true);
    try {
      const imageFile = NewsCategoryFormData.image?.[0];

      const payload: CreateNewsCategoryPayload = {
        newsCategoryTitle: {
          am: NewsCategoryFormData.NewsCategoryTitleAm || "",
          en: NewsCategoryFormData.NewsCategoryTitleEn || "",
        },
        newsCategoryDescription: {
          am: NewsCategoryFormData.NewsCategoryDescriptionAm || "",
          en: NewsCategoryFormData.NewsCategoryDescriptionEn || "",
        },
        // Only include fileInfo if there's a new image
        ...(imageFile && {
          fileInfo: {
            fileName: imageFile.name,
            contentType: imageFile.type,
            size: imageFile.size,
            originalname: imageFile.name,
          },
        }),
        isActive: NewsCategoryFormData.isActive,
        color: NewsCategoryFormData.color,
      };

      await updateItem({
        id: item.id,
        data: payload,
        ...(imageFile && { imageFile }),
      });

      toast.success("News category updated successfully");
      navigate(-1);
    } catch (error) {
      toast.error("Failed to update news category");
      console.error("Update error:", error);
      setIsSubmitting(false);
    }
  };
  const onCancel = () => {
    navigate(-1);
  };
  return (
    <NewsCategoryForm
      handleSubmit={handleSubmit(handleEditSubmit)}
      handleCancel={onCancel}
      watch={watch}
      setValue={setValue}
      control={control}
      register={register}
      errors={errors}
      isSubmitting={isSubmitting}
      label="Edit NewsCategory"
      item={item}
    />
  );
};
