import { useForm } from "react-hook-form";
import { ContactUsFormData, CreateContactUsPayload } from "../types/contactUs";
import { toast } from "sonner";
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { useContactUs } from "../hooks/useContactUs";
import ContactUsForm from "./Form";

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

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

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