"use client";

import React, { useState, useMemo, useEffect } from "react";
import { BreadcrumbBalmy } from "@/components/balmy";
import ProductCard from "@/components/ProductCard";
import SideFilter from "@/components/offers/side-filter";
import { useTranslations } from "next-intl";
import ProductGridSkeleton from "@/components/skeletons/product-grid-skeleton";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import useCategory from "@/hooks/use-category";
import { filterProductsByBrands } from "@/lib/brand-extractor";
import { useAppDispatch } from "@/store/hooks";
import { addToCart, setCartOpen } from "@/store/slices/cart-slice";
import { mapProductFromApi } from "@/lib/mappers/product-mapper";
import toast from "react-hot-toast";
import { usePathname } from "next/navigation";

type Props = { categoryId: string | number };

export default function CategoryPageClient({ categoryId }: Props) {
  const dispatch = useAppDispatch();
  const { loading, error, t, categoryProducts, fetchNextPage, hasMore } = useCategory(categoryId);
  const tNav = useTranslations("navigation");
  const tCat = useTranslations("category");
  const tProducts = useTranslations("products");
  const pathname = usePathname();
  const locale = pathname?.split("/")[1] || "ar";

  const [selectedCategories, setSelectedCategories] = useState<string[]>([]);
  const [selectedRatings, setSelectedRatings] = useState<number[]>([]);
  const [selectedPriceRanges, setSelectedPriceRanges] = useState<string[]>([]);
  const [selectedBrands, setSelectedBrands] = useState<string[]>([]);
  const [sortBy, setSortBy] = useState("suggestions");
  const [visibleCount, setVisibleCount] = useState(9);

  const products = categoryProducts?.data || [];
  const isFiltering =
    selectedRatings.length > 0 ||
    selectedPriceRanges.length > 0 ||
    selectedBrands.length > 0;

  // Filter products
  const filteredProducts = useMemo(() => {
    let filtered = products;

    // Rating filter
    if (selectedRatings.length > 0) {
      filtered = filtered.filter((product: any) => {
        const productRating = product.reviews?.average_rating || 0;
        return selectedRatings.some(
          (rating) => Math.floor(productRating) === rating
        );
      });
    }

    // Price filter
    if (selectedPriceRanges.length > 0) {
      filtered = filtered.filter((product: any) => {
        const price = Number(product.price) || 0;
        const range = selectedPriceRanges[0];
        if (range === "under-200" && price >= 200) return false;
        if (range === "200-400" && (price < 200 || price >= 400)) return false;
        if (range === "400-600" && (price < 400 || price >= 600)) return false;
        if (range === "over-600" && price < 600) return false;
        return true;
      });
    }

    // Brand filter using the new utility function
    if (selectedBrands.length > 0) {
      filtered = filterProductsByBrands(filtered, selectedBrands);
    }

    return filtered;
  }, [products, selectedRatings, selectedPriceRanges, selectedBrands]);

  // Reset visible count when filters change
  useEffect(() => {
    setVisibleCount(9);
  }, [selectedCategories, selectedRatings, selectedPriceRanges, selectedBrands, sortBy]);

  // Sort products
  const sortedProducts = useMemo(() => {
    const sorted = [...filteredProducts];

    switch (sortBy) {
      case "price-low-high":
        return sorted.sort((a, b) => a.price - b.price);
      case "price-high-low":
        return sorted.sort((a, b) => b.price - a.price);
      case "rating":
        return sorted.sort((a, b) => {
          const ratingA = a.reviews?.average_rating || 0;
          const ratingB = b.reviews?.average_rating || 0;
          return ratingB - ratingA;
        });
      case "newest":
        return sorted.sort((a, b) => (b.new ? 1 : 0) - (a.new ? 1 : 0));
      default:
        return sorted;
    }
  }, [filteredProducts, sortBy]);

  if (loading) {
    return (
      <div className="min-h-screen bg-white">
        <div className="container mx-auto px-4 pt-32 pb-12">
          <ProductGridSkeleton count={9} />
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="min-h-screen bg-white flex items-center justify-center">
        <p className="text-base md:text-lg xl:text-xl text-center text-red-600">
          {t("error-loading-products") || "Error loading products. Please try again."}
        </p>
      </div>
    );
  }

  const breadcrumbItems = [
    { label: tNav("home"), href: `/${locale}/home` },
    { label: categoryProducts?.category?.name || tCat("title"), href: `/${locale}/category/${categoryId}` },
  ];

  const visibleProducts = sortedProducts.slice(0, visibleCount);

  const handleLoadMore = () => {
    if (visibleCount < sortedProducts.length) {
      setVisibleCount((prev) => prev + 9);
    } else if (!isFiltering && hasMore) {
      fetchNextPage();
    }
  };

  const handleAddToCart = async (productId: number) => {
    try {
      await dispatch(addToCart({ productId, productQTY: 1 })).unwrap();
      toast.success(tProducts("added-to-cart") || "تمت الإضافة إلى السلة");
      dispatch(setCartOpen(true));
    } catch (error: any) {
      toast.error(error?.message || "Failed to add to cart");
      throw error;
    }
  };


  return (
    <div className="min-h-screen bg-white" dir={locale === "ar" ? "rtl" : "ltr"}>
      <div className="container mx-auto px-4 pt-32 pb-12">
        {/* Breadcrumb */}
        <div className="mb-8">
          <BreadcrumbBalmy items={breadcrumbItems} className="justify-start" />
        </div>

        {/* Mobile Filter Button - visible only on small screens */}
        <div className="lg:hidden mb-4">
          <SideFilter
            activeCategoryId={categoryId}
            selectedCategories={selectedCategories}
            selectedRatings={selectedRatings}
            selectedPriceRanges={selectedPriceRanges}
            selectedBrands={selectedBrands}
            onCategoryChange={setSelectedCategories}
            onRatingChange={setSelectedRatings}
            onPriceChange={setSelectedPriceRanges}
            onBrandChange={setSelectedBrands}
            products={products}
          />
        </div>

        {/* 2-Column Layout — sidebar first in DOM → inline-start side in both RTL/LTR */}
        <div className="flex flex-col lg:flex-row gap-10">
          {/* Sidebar (inline-start side: right in RTL, left in LTR) */}
          <aside className="hidden lg:block lg:w-[22%] flex-shrink-0">
            <div className="sticky top-28">
              <SideFilter
                activeCategoryId={categoryId}
                selectedCategories={selectedCategories}
                selectedRatings={selectedRatings}
                selectedPriceRanges={selectedPriceRanges}
                selectedBrands={selectedBrands}
                onCategoryChange={setSelectedCategories}
                onRatingChange={setSelectedRatings}
                onPriceChange={setSelectedPriceRanges}
                onBrandChange={setSelectedBrands}
                products={products}
              />
            </div>
          </aside>

          {/* Vertical divider line */}
          <div className="hidden lg:block w-px bg-gray-200 self-stretch" />

          {/* Main Content */}
          <main className="flex-1 min-w-0">
            {/* Top Bar - Sort + Count */}
            <div className="mb-6 flex flex-wrap items-center justify-between gap-4">
              {/* Sort Select */}
              <div className="flex items-center gap-3">
                <span className="text-sm font-medium text-black whitespace-nowrap">{tCat("sort-by")}:</span>
                <Select value={sortBy} onValueChange={setSortBy}>
                  <SelectTrigger className="w-[180px] border-gray-300">
                    <SelectValue placeholder={tCat("select-sort")} />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="suggestions">{tCat("suggestions")}</SelectItem>
                    <SelectItem value="price-low-high">
                      {tCat("price-low-to-high")}
                    </SelectItem>
                    <SelectItem value="price-high-low">
                      {tCat("price-high-to-low")}
                    </SelectItem>
                    <SelectItem value="rating">{tCat("rating")}</SelectItem>
                    <SelectItem value="newest">{tCat("newest")}</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <p className="text-sm text-gray-500">
                {tCat("products-showing", { count: sortedProducts.length })}
              </p>
            </div>

            {/* Product Grid - 3 products per row on desktop */}
            {visibleProducts.length > 0 ? (
              <>
                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
                  {visibleProducts.map((rawProduct: any) => {
                    const normalizedProduct = mapProductFromApi(rawProduct);
                    return (
                      <div key={normalizedProduct.id} className="w-full">
                        <ProductCard 
                          product={normalizedProduct} 
                          onAddToCart={handleAddToCart}
                        />
                      </div>
                    );
                  })}
                </div>

                {/* Load More Button */}
                {(visibleCount < sortedProducts.length || (!isFiltering && hasMore)) && (
                  <div className="flex justify-center mt-10">
                    <button
                      className="bg-black text-white px-16 py-3 rounded-lg font-medium hover:bg-gray-800 transition-colors duration-300 text-sm disabled:opacity-50"
                      onClick={handleLoadMore}
                      disabled={loading}
                    >
                      {loading ? tCat("loading-products") : tCat("load-more")}
                    </button>
                  </div>
                )}
              </>
            ) : (
              /* Empty State */
              <div className="flex flex-col items-center justify-center py-20 text-center min-h-[50vh]">
                <div className="text-6xl mb-4">🔍</div>
                <h3 className="text-xl font-bold text-black mb-2">
                  {tCat("no-results")}
                </h3>
                <p className="text-gray-500">
                  {selectedRatings.length > 0 || selectedBrands.length > 0 || selectedPriceRanges.length > 0
                    ? tCat("try-different-filters")
                    : tCat("no-products-found")}
                </p>
              </div>
            )}
          </main>
        </div>
      </div>
    </div>
  );
}
