"use client";
import fetchData from "@/api/fetch-data";
import postData from "@/api/post-data";
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { toastError, toastSuccess } from "@/services/custom-toast";
import { useLocale, useTranslations } from "next-intl";
import { useEffect, useRef, useState } from "react";
import { FaSpinner, FaTrash } from "react-icons/fa";
import AlertWarning from "../../shared/AlertWarning";
import Loading from "../../shared/Loading";
import AddLabel from "./AddLabel";
import AddValue from "./AddValue";

export default function FormFilters({ id }) {
  const [addedValue, setAddedValue] = useState(""); // Added value for `AddValue` component
  const [deletingIndex, setDeletingIndex] = useState(null); // Track the index of the item being deleted
  const [postLabelSuccess, setPostLabelSuccess] = useState(false); // Track the index of the item being deleted
  const [isSubmitting, setIsSubmitting] = useState(false); // Track the index of the item being deleted
  const [isProductLabelsLoading, setIsProductLabelsLoading] = useState(false); // Track the index of the item being deleted
  const [data, setData] = useState(null); // All fetched data
  const [existItems, setExistItems] = useState([]); // Existing product details
  const t = useTranslations("vendor");
  const e = useTranslations();
  const locale = useLocale();
  const processRef = useRef(false);

  // Fetch values and labels
  async function getValuesAndLabels() {
    setIsProductLabelsLoading(true);
    const { data, error, message } = await fetchData({
      endPoint: `/user/products/addtional-details/${id}`, //STATIC ID
      locale,
    });
    setIsProductLabelsLoading(false);
    if (data) {
      setIsProductLabelsLoading(false);
      setData(data);
      setPostLabelSuccess(false);
    }
    if (error) {
      setIsProductLabelsLoading(false);
      toastError(message);
      setPostLabelSuccess(false);
    }
  }

  useEffect(() => {
    getValuesAndLabels();
  }, [postLabelSuccess]);

  useEffect(() => {
    if (data && !processRef.current) {
      data?.product_details?.forEach((item) => {
        const label = data?.all_labels?.find(
          (label) => label.id == item.lable_id
        )?.data[0];
        setExistItems((prev) => [
          ...prev,
          {
            label,
            value: item.data[0],
            active: item.active,
            item_id: item.data[0].item_id,
          },
        ]);
      });
      processRef.current = true;
    }
  }, [data, addedValue]);
  if (isProductLabelsLoading) return <Loading />;

  // Filter data by language
  const langIdToFilter = locale === "en" ? "1" : "2";
  const filteredDataLabels = data?.all_labels?.flatMap((item) =>
    item.data.filter((dataItem) => dataItem.lang_id === langIdToFilter)
  );
  const filteredDataValues = data?.all_values?.flatMap((item) =>
    item.data.filter((dataItem) => dataItem.lang_id == langIdToFilter)
  );

  // Handle label and value selection
  const handleLabelChange = (index, newLabelId) => {
    setExistItems((prev) => {
      const updatedItems = [...prev];
      updatedItems[index].label = filteredDataLabels.find(
        (label) => label.id == newLabelId
      );
      return updatedItems;
    });
  };

  const handleValueChange = (index, newValue) => {
    setExistItems((prev) => {
      const updatedItems = [...prev];
      const isAddedValue = addedValue?.value == newValue;
      updatedItems[index].value = isAddedValue
        ? addedValue // Use `addedValue` directly if matched
        : filteredDataValues.find((value) => value.id == newValue);
      return updatedItems;
    });
  };

  // Handle component deletion
  const handleDeleteLabel = async (index) => {
    setDeletingIndex(index);
    const itemToDelete = existItems[index];
    const formData = new FormData();
    if (itemToDelete.label) {
      formData.append(
        "label_id",
        itemToDelete.value?.item_id || itemToDelete.label?.lable_id
      );
      formData.append("product_id", id);
    }
    const res = await postData({
      endPoint: "/user/products/addtional-details/delete",
      locale,
      body: formData,
    });

    setDeletingIndex(null);
    if (!res.error) {
      toastSuccess(t("deletedSuccess"));
      setExistItems((prev) => prev.filter((_, i) => i !== index));
    } else {
      toastError(res.message || "Failed to delete the item");
    }
  };

  // Submit all labels and values
  const submitValues = async () => {
    setIsSubmitting(true);
    const payload = existItems.map((item) => ({
      labelId: item?.label?.lable_id,
      value: item.value?.value,
      item_id: item.item_id,
      active: item.active,
    }));

    const formData = new FormData();
    for (let item of payload) {
      const isExistedLabel = data.product_details.some(
        (detail) => detail.id == item.item_id
      );
      formData.append("id", id);
      if (!isExistedLabel) {
        formData.append("title[new][]", item.labelId);
        formData.append("detail[new][]", item.value);
        formData.append("filter[new][]", item.active);
      } else {
        formData.append(`title[${item.item_id}][]`, item.labelId);
        formData.append(`detail[${item.item_id}][]`, item.value);
        formData.append(`filter[${item.item_id}][]`, item.active);
      }
    }

    const res = await postData({
      endPoint: "/user/products/addtional-details",
      locale,
      body: formData,
    });
    setIsSubmitting(false);
    if (res.error) {
      setIsSubmitting(false);
      toastError(res.message);
    } else {
      toastSuccess(res.message);
      setIsSubmitting(false);
    }
  };
  return (
    <section className="px-4 py-8 md:px-8">
      <div className="flex flex-wrap gap-4 ">
        <AddLabel success={setPostLabelSuccess} />
        <AddValue setValue={setAddedValue} />
      </div>

      <div className=" mt-5 md:mt-10 md:w-3/4">
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-4 ">
          <h2 className="max-md:hidden">{t("title")}</h2>
          <h2 className="max-md:hidden">{t("value")}</h2>
          <h2 className="max-md:hidden">{t("active")}</h2>
          <button
            onClick={() =>
              setExistItems((prev) => [
                ...prev,
                { active: "0", label: null, value: null },
              ])
            }
            className="bg-green-600 text-white hover:bg-green-500 p-2 rounded-md w-full md:w-28"
          >
            {t("add")}
          </button>
        </div>
        {existItems.length > 0 && !isProductLabelsLoading ? (
          <>
            {existItems
              ?.map((item, i) => (
                <div
                  key={i}
                  className="gap-4 my-2 border-t py-4 rounded-md grid grid-cols-1 md:grid-cols-4 "
                >
                  <h2 className="md:hidden">{t("title")}</h2>

                  <Select
                    value={item.label?.id || ""}
                    onValueChange={(newValue) => handleLabelChange(i, newValue)}
                    className="w-full md:w-48"
                  >
                    <SelectTrigger>
                      <SelectValue placeholder={t("selectlabel")}>
                        {item.label?.title || t("selectlabel")}
                      </SelectValue>
                    </SelectTrigger>
                    <SelectContent>
                      <SelectGroup>
                        {filteredDataLabels?.map((dataItem) => (
                          <SelectItem key={dataItem.id} value={dataItem.id}>
                            {dataItem.title}
                          </SelectItem>
                        ))}
                      </SelectGroup>
                    </SelectContent>
                  </Select>
                  <h2 className="md:hidden">{t("value")}</h2>

                  <Select
                    value={item.value?.id || addedValue?.value || ""}
                    onValueChange={(newValue) => handleValueChange(i, newValue)}
                    className="w-full md:w-28"
                  >
                    <SelectTrigger>
                      <SelectValue placeholder={t("selectvalue")}>
                        {item.value?.value || t("selectvalue")}
                      </SelectValue>
                    </SelectTrigger>
                    <SelectContent>
                      <SelectGroup>
                        {addedValue && (
                          <SelectItem value={addedValue.value}>
                            {addedValue.value}
                          </SelectItem>
                        )}
                        {filteredDataValues?.map((dataItem) => (
                          <SelectItem key={dataItem.id} value={dataItem.id}>
                            {dataItem.value}
                          </SelectItem>
                        ))}
                      </SelectGroup>
                    </SelectContent>
                  </Select>
                  <div className="flex gap-x-2 items-center justify-between">
                    <div className="flex gap-x-2">
                      <h2 className="md:hidden">{t("active")}</h2>
                      <input
                        type="checkbox"
                        className=" size-6"
                        checked={item.active == 1}
                        onChange={(e) =>
                          setExistItems((prev) => {
                            const updatedItems = [...prev];
                            updatedItems[i].active = e.target.checked ? 1 : 0;
                            return updatedItems;
                          })
                        }
                      />
                    </div>
                    {/* Mobiles screen */}
                    <button
                      onClick={() => handleDeleteLabel(i)}
                      disabled={deletingIndex !== null && deletingIndex !== i}
                      className={`md:hidden rounded-md p-2 w-28 flex justify-center items-center ${
                        deletingIndex === i
                          ? "opacity-50"
                          : "border-2 border-red-600 text-red-600 duration-200 transition-all hover:text-white hover:bg-red-500"
                      }`}
                    >
                      {deletingIndex === i ? (
                        <FaSpinner className="animate-spin" />
                      ) : (
                        <FaTrash />
                      )}
                    </button>
                  </div>
                  {/* Large screens */}
                  <button
                    onClick={() => handleDeleteLabel(i)}
                    disabled={deletingIndex !== null && deletingIndex !== i}
                    className={` max-md:hidden rounded-md p-2 w-28 flex justify-center items-center ${
                      deletingIndex === i
                        ? "opacity-50"
                        : "border-2 border-red-600 text-red-600 duration-200 transition-all hover:text-white hover:bg-red-500"
                    }`}
                  >
                    {deletingIndex === i ? (
                      <FaSpinner className="animate-spin" />
                    ) : (
                      <FaTrash />
                    )}
                  </button>
                </div>
              ))
              ?.reverse()}
          </>
        ) : (
          <AlertWarning text={e("nodata")} className={"m-0 "} />
        )}

        <div className="mt-6">
          <button
            onClick={submitValues}
            disabled={isSubmitting}
            className="w-full md:w-28 h-10 btn btn-btnColor  text-white p-2 rounded-md"
          >
            {isSubmitting ? (
              <FaSpinner className="animate-spin m-auto" />
            ) : (
              t("save")
            )}
          </button>
        </div>
      </div>
    </section>
  );
}
