"use client";
import postData from "@/api/post-data";
import { useFilter } from "@/stores/productsFilter";
import clsx from "clsx";
import { useLocale, useTranslations } from "next-intl";
import { useEffect, useState } from "react";
import { BsGrid3X3Gap } from "react-icons/bs";
import { FaSpinner } from "react-icons/fa";
import { LuLayoutGrid } from "react-icons/lu";
import { TfiLayoutGrid4 } from "react-icons/tfi";
import { TiThMenuOutline } from "react-icons/ti";
import AlertWarning from "../shared/AlertWarning";
import ProductCard from "../shared/ProductCard";

export default function ProductsLayout({
  data,
  isFilteredLoading,
  setIsFilteredLoading,
}) {
  const { filters } = useFilter();
  const [filteredProducts, setFilteredProducts] = useState(
    Array.isArray(data?.products?.data)
      ? data.products.data
      : Object.values(data.products.data)
  );
  const [currentPage, setCurrentPage] = useState(1); // Track current page
  const [productsColumns, setProductsColumns] = useState(4); // Track current page
  const [totalPages, setTotalPages] = useState(1); // Track total pages
  const locale = useLocale();
  const t = useTranslations("filter");
  const l = useTranslations();

  useEffect(() => {
    async function fetchFilteredProducts() {
      const formData = new FormData();
      // Append filters to formData as before
      if (filters.search?.length > 2) formData.append("search", filters.search);
      if (filters.size.length)
        formData.append("size[]", filters.size.join(","));
      for (let brand of filters.brand) {
        formData.append("brand[]", brand); // 1,2,3
      }
      // if (filters.brand.length) formData.append('brand[]', filters.brand.join(',')); // 1,2,3
      for (let label of filters.label) {
        formData.append("label[]", label); // 1,2,3
      }

      if (filters.max_price) formData.append("max_price", filters.max_price);
      if (filters.min_price) formData.append("min_price", filters.min_price);
      formData.append("page", currentPage); // Add current page to request
      const hasFilters =
        filters.search ||
        filters.size.length ||
        filters.brand.length ||
        filters.label.length ||
        filters.max_price ||
        filters.min_price;

      if (hasFilters) {
        setIsFilteredLoading(true);
        const filterRes = await postData({
          endPoint: "/search/filter",
          body: formData,
          locale,
        });
        const filteredData = Array.isArray(filterRes?.data?.products?.data)
          ? filterRes.data.products.data
          : Object.values(filterRes.data.products.data);
        setFilteredProducts(filteredData);
        setTotalPages(filterRes.data.products.last_page); // Set total pages from API
        setIsFilteredLoading(false);
      } else {
        setIsFilteredLoading(false);
        setFilteredProducts(
          Array.isArray(data.products.data)
            ? data.products.data
            : Object.values(data.products.data)
        );
        setTotalPages(1); // If no filters, assume only 1 page
      }
    }
    fetchFilteredProducts();
  }, [filters, locale, currentPage, data.products.data]); // Trigger fetch on currentPage change

  const handlePagination = (page) => {
    if (page >= 1 && page <= totalPages) {
      setCurrentPage(page);
    }
  };
  const getLayoutButtonClass = (columns) => {
    return clsx(
      "p-2 rounded-lg transition-all duration-500 transform relative",
      "hover:bg-secondary hover:shadow-lg",
      {
        "text-light scale-125 shadow-md bg-secondary":
          productsColumns === columns,
        "text-gray-400 hover:text-light hover:scale-110":
          productsColumns !== columns,
        "after:content-[''] after:absolute after:inset-0 after:rounded-lg after:ring-2 after:ring-main/40 after:opacity-0 after:transition-opacity after:duration-300": true,
      }
    );
  };

  const getProductCardClass = (index) => {
    return clsx(
      // Base classes
      `transform opacity-0 motion-safe:animate-layout-transition hover:shadow-lg transition-all duration-700 ease-in-out animate-in fade-in-0 zoom-in-95 delay-[${
        index * 2
      }ms]`,
      {
        "col-span-12 md:col-span-12 opacity-100 lg:col-span-12":
          productsColumns == 1,
        "col-span-12 md:col-span-6 opacity-100 lg:col-span-6 2xl:col-span-6":
          productsColumns == 2,
        "col-span-12 md:col-span-6 opacity-100 lg:col-span-4 2xl:col-span-4":
          productsColumns == 3,
        "col-span-12 md:col-span-6 opacity-100 lg:col-span-4 2xl:col-span-3":
          productsColumns == 4,
      }
    );
  };

  return (
    <div className="relative">
      {/* Loading button styles enhanced */}
      <button
        className={clsx(
          "bg-gradient-to-r from-main/80 gap-1 to-main text-light font-bold p-2 shadow-lg",
          "flex items-center transition-all duration-500 fixed z-[9999999] top-0",
          "rounded-b-lg start-1/2 transform -translate-x-1/2",
          "hover:shadow-xl hover:from-main hover:to-main/80",
          {
            "invisible opacity-0": !isFilteredLoading,
            "visible opacity-100": isFilteredLoading,
          }
        )}
      >
        <h4 className="animate-pulse">{l("loading")}</h4>
        <FaSpinner className="animate-spin ml-2" />
      </button>

      <div className="flex justify-between items-center mb-5">
        <div className="flex bg-gray-100 p-3 rounded-lg items-center gap-4 shadow-sm hover:shadow-md transition-shadow duration-300">
          <p className="text-gray-400 text-xl">{t("product")}</p>
          <div className="flex items-center gap-3 bg-white/50 p-2 rounded-lg">
            <button
              onClick={() => setProductsColumns(1)}
              className={getLayoutButtonClass(1) + " max-md:hidden"}
            >
              <TiThMenuOutline size={20} />
            </button>
            <button
              onClick={() => setProductsColumns(2)}
              className={getLayoutButtonClass(2) + " max-md:hidden"}
            >
              <LuLayoutGrid size={20} />
            </button>
            <button
              onClick={() => setProductsColumns(3)}
              className={getLayoutButtonClass(3) + " max-lg:hidden"}
            >
              <BsGrid3X3Gap size={20} />
            </button>
            <button
              onClick={() => setProductsColumns(4)}
              className={getLayoutButtonClass(4) + "max-2xl:hidden"}
            >
              <TfiLayoutGrid4 size={20} />
            </button>
          </div>
        </div>
      </div>

      {/* Products grid with enhanced transitions */}
      <div>
        <div className="grid grid-cols-12 gap-6">
          {filteredProducts?.length > 0 ? (
            filteredProducts.map((product, index) => (
              <div key={product.id} className={getProductCardClass(index)}>
                <div className="product-card-container h-full">
                  <ProductCard product={product} h={productsColumns == 1} />
                </div>
              </div>
            ))
          ) : (
            <div className="p-2 col-span-12">
              {filteredProducts.length == 0 ? (
                <AlertWarning
                  className={"mx-0 w-full"}
                  text={t("noproducts")}
                />
              ) : (
                <div className="col-span-12 w-full flex items-center justify-center h-[50vh]">
                  <div className="loader"></div>
                </div>
              )}
            </div>
          )}
        </div>
        {/* Pagination Controls with enhanced styling */}
        <div className="flex justify-center gap-4 items-center mt-8">
          <button
            onClick={() => handlePagination(currentPage - 1)}
            disabled={currentPage === 1}
            className={clsx(
              "px-4 py-2 rounded-lg transition-all duration-300 transform",
              "hover:shadow-md hover:scale-105 active:scale-95",
              currentPage === 1
                ? "bg-gray-200 text-gray-400 cursor-not-allowed"
                : "bg-gray-300 text-gray-600 hover:bg-gray-400 hover:text-light"
            )}
          >
            {t("prev")}
          </button>
          <p className="text-gray-400 bg-gray-100 px-4 py-2 rounded-lg">
            {t("page")} {currentPage} {t("from")} {totalPages}
          </p>
          <button
            onClick={() => handlePagination(currentPage + 1)}
            disabled={currentPage === totalPages}
            className={clsx(
              "px-4 py-2 rounded-lg transition-all duration-300 transform",
              "hover:shadow-md hover:scale-105 active:scale-95",
              currentPage === totalPages
                ? "bg-gray-200 text-gray-400 cursor-not-allowed"
                : "bg-gray-300 text-gray-600 hover:bg-gray-400 hover:text-light"
            )}
          >
            {t("next")}
          </button>
        </div>
      </div>
    </div>
  );
}
