"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 { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";

import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { CustomDropZone } from "@/components/ui/FormInput/Inputs";

// API
import { getCategories } from "@/Services/Categories/ApiCategory";
import { addProducts, editProducts } from "@/Services/Products/ApiProducts";

import { useModal } from "@/context/ModalProvider";

import CustomInput from "@/components/ui/FormInput/CustomInput";
import MultiSelect from "@/components/ui/FormInput/MultiSelectNew";
import AddMeta from "../Meta/AddMeta";
import { getMetas } from "@/Services/Meta/ApiMeta";

// Validation Schema
const schema = yup.object({
  name: yup.string().required("Product name is required"),
  description: yup.string().nullable(),
  category_id: yup.string().required("Category is required"),
  product_url: yup.string().required("Product url is required"),
  video_url: yup.string().nullable(),
  product_image: yup
    .object({
      product_image: yup
        .array()
        .of(yup.mixed().required("Image is required"))
        .min(1, "Image is required")
        .required("Image is required"),
    })
    .required("Image is required"),
  status: yup.boolean().default(true),
});

export default function AddProduct({ type = "add", editData = null }) {
  const { openModal, closeModal } = useModal();
  const queryClient = useQueryClient();

  const {
    register,
    handleSubmit,
    control,
    reset,
    setValue,
    watch,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(schema),
    defaultValues: {
      product_image: null,
      status: true,
    },
  });

  const nameWatch = watch("name");

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

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

      setValue("product_url", formattedName);
    }
  }, [nameWatch, editData]);

  const [imageFile, setImageFile] = useState({
    product_image: editData?.product_image ? [editData.product_image] : [],
  });
  // Image UseEffect
  useEffect(() => {
    // if (imageFile && imageFile?.product_image?.length > 0) {
    setValue("product_image", imageFile);
    // }
  }, [imageFile, setValue]);

  useEffect(() => {
    if (type === "edit" && editData) {
      Object.keys(editData).forEach((fieldName) => {
        setValue(fieldName, editData[fieldName]);
      });

      setValue("category_id", editData.category_id);

      const productImages = editData.product_image
        ? editData.product_image.split(",")
        : [];

      setImageFile({
        product_image: productImages,
      });
    }
  }, [type, editData, setValue]);

  const { data: categories = [] } = useQuery({
    queryKey: ["categories"],
    queryFn: () => getCategories(0, 10, false, true),
  });

  const addmutation = useMutation({
    mutationFn: addProducts,
    onSuccess: (data) => {
      queryClient.invalidateQueries("products");
      reset();
      setImageFile(false);
    },
    onError: (error) => {},
  });
  const editMutation = useMutation({
    mutationFn: (data) => editProducts(data, editData.id),

    onSuccess: (data) => {
      queryClient.invalidateQueries("products");
      reset();

      setImageFile(false);
      closeModal();
    },
    onError: (error) => {},
  });

  const onSubmit = async (data) => {
    const formData = new FormData();
    formData.append("folder", "products");
    formData.append("name", data.name);
    formData.append("description", data.description || "");
    formData.append("category_id", data.category_id);
    formData.append("product_url", data.product_url);
    formData.append("video_url", data.video_url);
    formData.append("status", data.status ? "1" : "0");

    const uploadedImages =
      data.product_image?.product_image || imageFile?.product_image || [];

    uploadedImages.forEach((file) => {
      if (file instanceof File) {
        formData.append("product_image", file);
      } else {
        formData.append("existing_images", file);
      }
    });

    const wantsMeta = window.confirm(
      "Do you want to add meta tags for this product?"
    );
    if (wantsMeta) {
      let metaEditData = editData;

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

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

      // ✅ Now pass enriched editData to AddMeta
      openModal(
        <AddMeta
          parent
          editData={metaEditData}
          onClose={closeModal}
          type={type}
          onSubmit={(metaFormData) => {
            for (let [key, value] of metaFormData.entries()) {
              formData.append(key, value);
            }
            if (type === "add") {
              addmutation.mutate(formData);
            } else {
              formData.append("id", editData.id);
              editMutation.mutate(formData);
            }

            closeModal();
          }}
        />
      );
    } else {
      if (type === "add") {
        addmutation.mutate(formData);
      } else {
        formData.append("id", editData.id);
        editMutation.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"} Product
        </h2>
        <div className="flex items-center space-x-2 ">
          <label className="text-sm font-medium">Active</label>
          <Controller
            control={control}
            name="status"
            render={({ field }) => (
              <Switch checked={field.value} onCheckedChange={field.onChange} />
            )}
          />
        </div>
      </div>

      <form onSubmit={handleSubmit(onSubmit)} className="space-y-6 p-6">
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          <div>
            <Controller
              name={`name`}
              control={control}
              render={({ field }) => {
                return (
                  <CustomInput
                    {...field}
                    label="Product Name"
                    type="text"
                    placeholder="Enter Product Name"
                    value={field.value}
                    errors={errors}
                    required
                  />
                );
              }}
            />
          </div>

          <Controller
            name="category_id"
            control={control}
            render={({ field }) => (
              <MultiSelect
                {...field}
                label="Category"
                options={
                  categories?.rows
                    ? categories.rows.map((cat) => {
                        return {
                          label: cat.category_name,
                          value: cat.id,
                        };
                      })
                    : []
                }
                isSearchable
                errors={errors}
                required
              />
            )}
          />

          {/* Product Image */}
          <div className="">
            <CustomDropZone
              name="product_image"
              label="Product Image"
              number_of_images={5}
              errors={errors}
              // type="add"
              fileType="image"
              image_size={2 * 1024 * 1024}
              uploadedFiles={imageFile}
              setUploadedFiles={setImageFile}
              // setUploadedFiles={(files) => {
              //   setImageFile(files);
              //   setValue("product_image", files);
              // }}
              required
            />
          </div>
          <Controller
            name="video_url"
            control={control}
            render={({ field }) => {
              return (
                <CustomInput
                  {...field}
                  label="Product Video URL"
                  type="url"
                  placeholder="Enter Product Video URL"
                  value={field.value}
                  errors={errors}
                />
              );
            }}
          />

          {/* Description */}
          <div className="md:col-span-2 lg:col-span-3">
            <Controller
              name={`description`}
              control={control}
              render={({ field }) => {
                return (
                  <CustomInput
                    {...field}
                    label="Description"
                    type="textarea"
                    placeholder="Enter Description"
                    value={field.value}
                    errors={errors}
                  />
                );
              }}
            />
          </div>
        </div>

        <div className="flex justify-end">
          <Button
            onClick={() => {
              reset();
              setImageFile(false);
            }}
            type="reset"
            className="mr-2 bg-red-700"
          >
            Reset
          </Button>
          <Button type="submit" variant="dark">
            Save
          </Button>
        </div>
      </form>
    </div>
  );
}
