"use client";
import { useEffect, useState } from "react";
import { useForm, Controller } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import {
  createCategory,
  editCategory,
} from "@/Services/Categories/ApiCategory";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { CustomDropZone } from "@/components/ui/FormInput/Inputs";
import CustomInput from "@/components/ui/FormInput/CustomInput";
import AddMeta from "../Meta/AddMeta";
import { useModal } from "@/context/ModalProvider";
import { getMetas } from "@/Services/Meta/ApiMeta";

const schema = yup.object({
  name: yup.string().required("Category name is required"),
  category_status: yup.boolean().default(true),
  // category_image: yup.mixed().nullable(),
  // category_image: yup
  //   .array()
  //   .of(yup.mixed().required("Image is required"))
  //   .min(1, "Image is required")
  //   .required("Image is required"),
  category_image: yup.object({
    category_image: yup
      .array()
      .of(yup.mixed().required("Image is required"))
      .min(1, "Image is required")
      .required("Image is required"),
  }),
  description: yup.string().required("Description is required"),
});

export default function AddCategoryForm({
  type = "add",
  editData = null,
  parent_id = null,
  onClose,
}) {
  const queryClient = useQueryClient();

  const { openModal, closeModal } = useModal();

  const {
    register,
    control,
    handleSubmit,
    reset,
    setValue,
    watch,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(schema),
    defaultValues: {
      name: "",
      parent_id: parent_id,
      category_url: "",
      category_status: true,
      category_image: null,
      description: "",
    },
  });


  const nameWatch = watch("name");

  useEffect(() => {
    if (editData?.category_url) {
      setValue("category_url", editData.category_url);
    }
  }, [editData]);

  useEffect(() => {
    if (nameWatch !== editData?.name) {
      const formatted = nameWatch
        ?.trim()
        .replace(/[^a-zA-Z0-9 ]/g, "")
        .replace(/\s+/g, "-")
        .toLowerCase();
      setValue("category_url", formatted);
    }
  }, [nameWatch]);

  const [imageFile, setImageFile] = useState({
    category_image: editData?.category_image ? [editData.category_image] : [],
  });

  useEffect(() => {
    setValue("category_image", imageFile);
  }, [imageFile, setValue]);

  useEffect(() => {
    if (editData) {
      reset({
        ...editData,
        category_status: editData.category_status === 1,
        category_image: {
          category_image: editData.category_image
            ? [editData.category_image]
            : [],
        },
      });
      setImageFile({
        category_image: editData.category_image
          ? [editData.category_image]
          : [],
      });
    } else {
      reset({
        name: "",
        parent_id,
        category_url: "",
        category_status: true,
        category_image: null,
        description: "",
      });
    }
  }, [editData, parent_id, reset]);

  const addMutation = useMutation({
    mutationFn: createCategory,
    onSuccess: () => {
      queryClient.invalidateQueries(["categories"]);
      reset();
      onClose();
    },
  });

  const editMutation = useMutation({
    mutationFn: editCategory,
    onSuccess: () => {
      queryClient.invalidateQueries(["categories"]);
      reset();
      onClose();
    },
  });

  // const onSubmit = (data) => {
  //   const formData = new FormData();
  //   formData.append("folder", "categories");
  //   formData.append("name", data.name);
  //   formData.append("category_url", data.category_url || "");
  //   formData.append("category_status", data.category_status ? "1" : "0");
  //   formData.append("parent_id", data.parent_id || "");
  //   formData.append("description", data.description);
  //   formData.append(
  //     "category_image",
  //     data.category_image instanceof File
  //       ? data.category_image
  //       : data.category_image?.category_image?.[0]
  //   );

  //   if (editData?.id) {
  //     formData.append("id", editData.id);
  //     editMutation.mutate(formData);
  //   } else {
  //     addMutation.mutate(formData);
  //   }
  // };

  const onSubmit = async (data) => {
    const formData = new FormData();
    formData.append("folder", "categories");
    formData.append("name", data.name);
    formData.append("category_url", data.category_url || "");
    formData.append("category_status", data.category_status ? "1" : "0");
    formData.append("parent_id", data.parent_id || "");
    formData.append("description", data.description);

    if (
      data.category_image instanceof File ||
      data.category_image?.category_image?.[0]
    ) {
      formData.append(
        "category_image",
        data.category_image instanceof File
          ? data.category_image
          : data.category_image.category_image[0]
      );
    }

    const wantsMeta = window.confirm(
      "Do you want to add meta tags for this category?"
    );

    if (wantsMeta) {
      let metaEditData = editData;

      if (type === "edit") {
        try {
          const meta = await getMetas(0, 1, {
            reference_type: "category",
            reference_id: editData?.category_url || data.category_url,
          });

          if (meta?.rows?.[0]) {
            metaEditData = {
              ...editData,
              metas: meta.rows[0].metas,
            };
          }
        } catch (err) {
          console.error("Failed to fetch meta for category:", err);
        }
      }

      openModal(
        <AddMeta
          parent
          editData={metaEditData}
          onClose={closeModal}
          type={type}
          onSubmit={(metaFormData) => {
            for (let [key, value] of metaFormData.entries()) {
              formData.append(key, value);
            }
            if (editData?.id) {
              formData.append("id", editData.id);
              editMutation.mutate(formData);
            } else {
              addMutation.mutate(formData);
            }

            closeModal();
          }}
        />
      );
    } else {
      if (editData?.id) {
        formData.append("id", editData.id);
        editMutation.mutate(formData);
      } else {
        addMutation.mutate(formData);
      }
    }
  };

  return (
    <div className="bg-white pt-0 w-full border border-gray-200 rounded-md ">
      <div className="flex justify-between items-center border-b p-4 bg-brand-dark/5">
        <h2 className="text-xl font-semibold text-brand-dark">
          {type === "add" ? "Add" : "Edit"} Category
        </h2>

        <Controller
          control={control}
          name="category_status"
          render={({ field }) => (
            <div className="flex items-center space-x-2">
              <label className="text-sm">Active</label>
              <Switch checked={field.value} onCheckedChange={field.onChange} />
            </div>
          )}
        />
      </div>
      <form onSubmit={handleSubmit(onSubmit)} className="p-6 space-y-6">
        <Controller
          name="name"
          control={control}
          render={({ field }) => (
            <CustomInput
              {...field}
              label="Category Name"
              errors={errors}
              required
            />
          )}
        />

        <Controller
          name="description"
          control={control}
          render={({ field }) => (
            <CustomInput
              {...field}
              label="Description"
              type="textarea"
              errors={errors}
              required
            />
          )}
        />

        <CustomDropZone
          name="category_image"
          label="Category Image"
          number_of_images={1}
          errors={errors}
          fileType="image"
          image_size={1024 * 1024 * 2}
          uploadedFiles={imageFile}
          setUploadedFiles={setImageFile}
          showIcon={false}
          required
        />

        <Button variant="dark" type="submit" className="w-full">
          {editData ? "Update" : "Add"} Category
        </Button>
      </form>
    </div>
  );
}
