"use client";

import { useState } from "react";
import Link from "next/link";
import Image from "next/image";
import { ChevronLeft, ChevronRight, Filter } from "lucide-react";
import { Button } from "@/components/ui/button";
import AccordionFilter from "@/components/ui/Custom/AccordianFilter";
import {
  Sheet,
  SheetContent,
  SheetTitle,
  SheetTrigger,
} from "@/components/ui/sheet";

// Utility: collect category and its child IDs
const collectCategoryIds = (category) => {
  const ids = [category.id];
  const traverse = (children) => {
    for (const child of children || []) {
      ids.push(child.id);
      if (child.children?.length) traverse(child.children);
    }
  };
  traverse(category.children);
  return ids;
};

// Utility: find category node by ID
const findCategoryById = (categories, id) => {
  for (const cat of categories) {
    if (cat.id === id) return cat;
    if (cat.children?.length) {
      const found = findCategoryById(cat.children, id);
      if (found) return found;
    }
  }
  return null;
};

export default function MainProductView({
  categories = [],
  products = [],
  categoryTree = [],
  collection = null, // ✅ collection input
}) {
  const [hoveredProduct, setHoveredProduct] = useState(null);
  const [selectedCategories, setSelectedCategories] = useState([]);
  const [currentPage, setCurrentPage] = useState(1);
  const productsPerPage = 12;

  const handleMouseEnter = (id) => setHoveredProduct(id);
  const handleMouseLeave = () => setHoveredProduct(null);

  const getProductImages = (productImageStr) =>
    productImageStr?.split(",").map((img) => img.trim()) || [];

  const getCurrentImage = (product) => {
    const images = getProductImages(product.product_image);
    return hoveredProduct === product.id && images.length > 1
      ? images[1]
      : images[0];
  };

  const selectedCategoryIds = selectedCategories.flatMap((id) => {
    const cat = findCategoryById(categoryTree, id);
    return cat ? collectCategoryIds(cat) : [];
  });

  const filteredProducts = products.filter((p) =>
    selectedCategories.length === 0
      ? true
      : selectedCategoryIds.includes(p.category_id)
  );

  const totalPages = Math.ceil(filteredProducts.length / productsPerPage);
  const indexOfLastProduct = currentPage * productsPerPage;
  const indexOfFirstProduct = indexOfLastProduct - productsPerPage;
  const currentProducts = filteredProducts.slice(
    indexOfFirstProduct,
    indexOfLastProduct
  );

  const paginate = (pageNumber) => {
    if (pageNumber < 1 || pageNumber > totalPages) return;
    setCurrentPage(pageNumber);
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  const pageNumbers = [];
  const displayPageRange = 5;
  let startPage = Math.max(1, currentPage - Math.floor(displayPageRange / 2));
  let endPage = startPage + displayPageRange - 1;

  if (endPage > totalPages) {
    endPage = totalPages;
    startPage = Math.max(1, endPage - displayPageRange + 1);
  }

  for (let i = startPage; i <= endPage; i++) {
    pageNumbers.push(i);
  }

  return (
    <div className="w-full">
      <div className="container mx-auto px-4 py-8">
        <div className="flex flex-col lg:flex-row gap-8">
          {/* Sidebar filter for desktop */}
          <div className="hidden lg:block lg:w-1/5">
            <div className="sticky top-40">
              <h2 className="text-xl mb-4 uppercase font-cormorant text-black font-medium tracking-wide">
                Categories
              </h2>

              <AccordionFilter
                data={categoryTree}
                selected={selectedCategories}
                onChange={(newIds) => {
                  setSelectedCategories(newIds);
                  setCurrentPage(1);
                }}
                labelKey="name"
                valueKey="id"
                childrenKey="children"
                countKey="count"
              />
            </div>
          </div>

          {/* Main Product Content */}
          <div className="lg:w-4/5">
            {/* ✅ Mobile filter button */}
            <div className="lg:hidden mb-4 flex justify-end">
              <Sheet>
                <SheetTrigger asChild>
                  <Button variant="dark" className="flex items-center gap-2">
                    <Filter size={16} />
                    Filter
                  </Button>
                </SheetTrigger>
                <SheetContent side="right" className="w-80">
                  <SheetTitle className="text-lg font-semibold mb-4 bg-brand-dark p-4 text-white">
                    Filter Categories
                  </SheetTitle>
                  <div className="px-4">
                    <AccordionFilter
                      data={categoryTree}
                      selected={selectedCategories}
                      onChange={(newIds) => {
                        setSelectedCategories(newIds);
                        setCurrentPage(1);
                      }}
                      labelKey="name"
                      valueKey="id"
                      childrenKey="children"
                      countKey="count"
                    />
                  </div>
                </SheetContent>
              </Sheet>
            </div>

            {/* Product grid */}
            <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
              {currentProducts.length > 0 ? (
                currentProducts.map((product) => (
                  <div key={product.id} className="group">
                    <Link href={`/${product.product_url}`} className="block">
                      <div
                        className="h-full p-2"
                        onMouseEnter={() => handleMouseEnter(product.id)}
                        onMouseLeave={handleMouseLeave}
                      >
                        <div className="relative">
                          <div className="relative w-full pt-[100%]">
                            <Image
                              src={getCurrentImage(product)?.replace("/api", "")}
                              alt={product.name}
                              fill
                              loading="lazy"
                              sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
                              className="absolute inset-0 object-cover transition-opacity duration-300"
                            />
                            {collection?.offers_percentage &&
                              collection?.visibility?.show_offers === 1 && (
                                <div className="absolute top-2 right-2 bg-red-600 text-white text-xs px-2 py-1">
                                  {parseFloat(
                                    collection.offers_percentage
                                  ).toFixed(0)}
                                  %
                                </div>
                              )}
                          </div>
                        </div>
                        <div className="flex flex-col items-center p-4">
                          <div className="text-center font-medium text-sm uppercase tracking-wider group-hover:text-brand-dark transition-colors">
                            {product.name}
                          </div>
                        </div>
                      </div>
                    </Link>
                  </div>
                ))
              ) : (
                <div className="col-span-full text-center py-12 text-gray-500 text-sm font-medium">
                  No products available for the selected category.
                </div>
              )}
            </div>

            {/* Pagination controls */}
            {filteredProducts.length > productsPerPage && (
              <div className="mt-8 flex justify-center">
                <nav className="flex items-center gap-1">
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => paginate(currentPage - 1)}
                    disabled={currentPage === 1}
                    className="px-2 py-1"
                  >
                    <ChevronLeft className="h-4 w-4" />
                  </Button>
                  {pageNumbers.map((number) => (
                    <Button
                      key={number}
                      variant={currentPage === number ? "default" : "outline"}
                      size="sm"
                      onClick={() => paginate(number)}
                      className="px-3 py-1"
                    >
                      {number}
                    </Button>
                  ))}
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => paginate(currentPage + 1)}
                    disabled={currentPage === totalPages}
                    className="px-2 py-1"
                  >
                    <ChevronRight className="h-4 w-4" />
                  </Button>
                </nav>
              </div>
            )}

            {/* Product count */}
            <div className="mt-4 text-center text-sm text-gray-500">
              Showing {indexOfFirstProduct + 1}-
              {Math.min(indexOfLastProduct, filteredProducts.length)} of{" "}
              {filteredProducts.length} products
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
