import { useForm } from "react-hook-form";
import {
  CreateSocialMediaPayload,
  SocialMediaFormData,
} from "../types/socialMediaType";
import { toast } from "sonner";
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { useSocialMedia } from "../hooks/useSocialMedia";
import SocilaMediaForm from "./Form";

export const AddSocialMedia = () => {
  const {
    register,
    handleSubmit,
    formState: { errors },
    watch,
    control,
    setValue,
  } = useForm<SocialMediaFormData>({
    defaultValues: {
      nameAm: "",
      nameEn: "",
      link: "",
      type: "",
      isActive: false,
    },
  });
  const navigate = useNavigate();
  const { createItem, isCreating } = useSocialMedia();
  const [isSubmitting, setIsSubmitting] = useState(false);

  const handleCreateSubmit = async (
    SocialMediaFormData: SocialMediaFormData
  ) => {
    setIsSubmitting(true);
    try {
      const payload: CreateSocialMediaPayload = {
        name: {
          am: SocialMediaFormData.nameAm || "",
          en: SocialMediaFormData.nameEn || "",
        },
        type: SocialMediaFormData.type,
        link: SocialMediaFormData.link,

        isActive: SocialMediaFormData.isActive,
      };
      await createItem({
        data: payload,
      });
      toast.success(" created successfully");
      navigate(-1);
    } catch (error) {
      toast.error("Failed to create SocialMedia");
      console.error("Creation error:", error);
      setIsSubmitting(false);
    } finally {
      setIsSubmitting(false);
    }
  };
  const onCancel = () => {
    navigate(-1);
  };
  return (
    <SocilaMediaForm
      handleSubmit={handleSubmit(handleCreateSubmit)}
      handleCancel={onCancel}
      watch={watch}
      setValue={setValue}
      control={control}
      register={register}
      errors={errors}
      isSubmitting={isSubmitting}
      label="Add Social Media Information"
    />
  );
};
