import { useForm } from "react-hook-form";
import { CreateVisionPayload, VisionFormData } from "../types/visionType";
import { toast } from "sonner";
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { useVision } from "../hooks/useVision";
import VisionForm from "./Form";

export const AddVision = () => {
  const {
    register,
    handleSubmit,
    formState: { errors },
    watch,
    control,
    setValue,
  } = useForm<VisionFormData>({
    defaultValues: {
      visionTitleEn: "",
      visionTitleAm: "",
      visionDescriptionAm: "",
      visionDescriptionEn: "",
      isActive: false,
    },
  });
  const navigate = useNavigate();
  const { createItem, isCreating } = useVision();
  const [isSubmitting, setIsSubmitting] = useState(false);

  const handleCreateSubmit = async (VisionFormData: VisionFormData) => {
    setIsSubmitting(true);
    try {
      const payload: CreateVisionPayload = {
        visionTitle: {
          am: VisionFormData.visionTitleAm || "",
          en: VisionFormData.visionTitleEn || "",
        },
        visionDescription: {
          am: VisionFormData.visionDescriptionAm || "",
          en: VisionFormData.visionDescriptionEn || "",
        },

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