import { useForm } from "react-hook-form";
import {
  CreateNewsCategoryPayload,
  NewsCategoryFormData,
} from "../types/newsCategoryType";
import { toast } from "sonner";
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { useNewsCategory } from "../hooks/useNewsCategory";
import NewsCategoryForm from "./Form";

export const AddNewsCategory = () => {
  const {
    register,
    handleSubmit,
    formState: { errors },
    watch,
    control,
    setValue,
  } = useForm<NewsCategoryFormData>({
    defaultValues: {
      NewsCategoryTitleEn: "",
      NewsCategoryTitleAm: "",
      NewsCategoryDescriptionAm: "",
      NewsCategoryDescriptionEn: "",
      color: "",
      isActive: false,
    },
  });
  const navigate = useNavigate();
  const { createItem } = useNewsCategory();
  const [isSubmitting, setIsSubmitting] = useState(false);

  const handleCreateSubmit = async (
    NewsCategoryFormData: NewsCategoryFormData
  ) => {
    setIsSubmitting(true);
    try {
      const imageFile = NewsCategoryFormData.image?.[0];
      if (!imageFile) {
        throw new Error("images are required");
      }
      const payload: CreateNewsCategoryPayload = {
        newsCategoryTitle: {
          am: NewsCategoryFormData.NewsCategoryTitleAm || "",
          en: NewsCategoryFormData.NewsCategoryTitleEn || "",
        },
        newsCategoryDescription: {
          am: NewsCategoryFormData.NewsCategoryDescriptionAm || "",
          en: NewsCategoryFormData.NewsCategoryDescriptionEn || "",
        },
        fileInfo: {
          fileName: imageFile.name,
          contentType: imageFile.type,
          size: imageFile.size,
          originalname: imageFile.name,
        },
        isActive: NewsCategoryFormData.isActive,
        color: NewsCategoryFormData.color || "#007BFF",
      };
      await createItem({
        data: payload,
        imageFile: imageFile,
      });
      toast.success("News category created successfully");
      // Navigate back to the news category list
      navigate(-1);
    } catch (error) {
      toast.error("Failed to create NewsCategory");
      console.error("Creation error:", error);
      setIsSubmitting(false);
    } finally {
      setIsSubmitting(false);
    }
  };
  const onCancel = () => {
    navigate(-1);
  };
  return (
    <NewsCategoryForm
      handleSubmit={handleSubmit(handleCreateSubmit)}
      handleCancel={onCancel}
      watch={watch}
      setValue={setValue}
      control={control}
      register={register}
      errors={errors}
      isSubmitting={isSubmitting}
      label="Add News Category"
    />
  );
};
