import {
  Control,
  FieldErrors,
  useForm,
  UseFormRegister,
  UseFormReset,
  UseFormSetValue,
  UseFormWatch,
} from "react-hook-form";
import {
  CreateSocialMediaPayload,
  SocialMediaFormData,
  SocialMediaItem,
} from "../types/socialMediaType";
import { useSocialMedia } from "../hooks/useSocialMedia";
import { useNavigate, useParams } from "react-router-dom";
import { toast } from "sonner";
import { useEffect, useMemo, useState } from "react";
import SocilaMediaForm from "./Form";

export interface FormProps {
  watch: UseFormWatch<SocialMediaFormData>;
  control: Control<SocialMediaFormData>;
  setValue: UseFormSetValue<SocialMediaFormData>;
  register: UseFormRegister<SocialMediaFormData>;
  errors: FieldErrors<SocialMediaFormData>;
  reset?: UseFormReset<SocialMediaFormData>;
  handleSubmit: (e: React.FormEvent) => void;
  handleCancel: () => void;
  isSubmitting: boolean;
  item?: SocialMediaItem;
  label: string;
}
export const EditSocialMedia = () => {
  const { id } = useParams();
  const { singleItem: item, updateItem } = useSocialMedia(undefined, id);
  const [isSubmitting, setIsSubmitting] = useState<boolean>(false);
  const navigate = useNavigate();
  const defaultValues = useMemo(
    () => ({
      nameEn: item?.name?.en,
      nameAm: item?.name?.am,
      link: item?.link,
      type: item?.type,
      isActive: item?.isActive,
    }),
    [item] // 👈 recompute only when item changes
  );
  const {
    register,
    handleSubmit,
    watch,
    control,
    setValue,
    reset,
    formState: { errors },
  } = useForm<SocialMediaFormData>({
    defaultValues,
  });
  useEffect(() => {
    if (item) {
      reset(defaultValues);
    }
  }, [item, defaultValues, reset]);
  const handleEditSubmit = async (SocialMediaFormData: SocialMediaFormData) => {
    if (!item) return;
    setIsSubmitting(true);
    try {
      const payload: CreateSocialMediaPayload = {
        name: {
          am: SocialMediaFormData.nameAm || "",
          en: SocialMediaFormData.nameEn || "",
        },
        type: SocialMediaFormData.type,
        link: SocialMediaFormData.link,

        isActive: SocialMediaFormData.isActive,
      };

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