"use client";

import React, { useState, useMemo, useEffect } from "react";
import { useParams } from "next/navigation";
import { BreadcrumbBalmy } from "@/components/balmy";
import ProductCard from "@/components/ProductCard";
import SideFilter from "@/components/offers/side-filter";
import Loading from "@/components/loading";
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select";
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 { useTranslations } from "next-intl";

interface BrandCategoryClientProps {
    brandName: string;
}

/**
 * Client component for the brand category page.
 * Fetches products filtered by brand name and displays them
 * with the same layout as the regular category page.
 */
export default function BrandCategoryClient({ brandName }: BrandCategoryClientProps) {
    const dispatch = useAppDispatch();
    const params = useParams<{ locale: string }>();
    const locale = params?.locale || "ar";
    const tProducts = useTranslations("products");
    const tCat = useTranslations("category");
    const tNav = useTranslations("navigation");

    const [loading, setLoading] = useState(true);
    const [products, setProducts] = useState<any[]>([]);
    const [error, setError] = useState<string | null>(null);

    const [selectedRatings, setSelectedRatings] = useState<number[]>([]);
    const [selectedPriceRanges, setSelectedPriceRanges] = useState<string[]>([]);
    const [selectedBrands, setSelectedBrands] = useState<string[]>(
        brandName ? [brandName.toLowerCase()] : []
    );
    const [sortBy, setSortBy] = useState("suggestions");
    const [visibleCount, setVisibleCount] = useState(9);

    // Fetch products for this brand
    useEffect(() => {
        if (!brandName) {
            setLoading(false);
            return;
        }

        const fetchBrandProducts = async () => {
            setLoading(true);
            setError(null);

            try {
                const res = await fetch(
                    `/api/catalog/brandsearch?brand=${encodeURIComponent(brandName)}&locale=${locale}`
                );

                if (!res.ok) {
                    throw new Error("Failed to fetch brand products");
                }

                const data = await res.json();
                setProducts(data.products || []);
            } catch (err: any) {
                console.error("Brand search error:", err);
                setError(err.message || "Error loading products");
            } finally {
                setLoading(false);
            }
        };

        fetchBrandProducts();
    }, [brandName, locale]);

    // Filter products by rating and price
    const filteredProducts = useMemo(() => {
        return products.filter((product: any) => {
            if (selectedRatings.length > 0) {
                const productRating = product.reviews?.average_rating || 0;
                const matchesRating = selectedRatings.some(
                    (rating) => Math.floor(productRating) === rating
                );
                if (!matchesRating) return false;
            }

            if (selectedPriceRanges.length > 0) {
                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;
        });
    }, [products, selectedRatings, selectedPriceRanges]);

    // Reset visible count when filters change
    useEffect(() => {
        setVisibleCount(9);
    }, [selectedRatings, selectedPriceRanges, 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 <Loading fullScreen variant="spinner" size="xl" />;
    }

    const breadcrumbItems = [
        { label: tNav("home"), href: "/home" },
        { label: brandName || tCat("title"), href: "#" },
    ];

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

    const handleLoadMore = () => {
        setVisibleCount((prev) => prev + 9);
    };

    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 || tProducts("failed-to-add-to-cart"));
            throw error;
        }
    };

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

                {/* Brand Title */}
                <div className="mb-8">
                    <h1 className="text-3xl font-bold text-gray-900">{brandName}</h1>
                    <p className="text-gray-500 mt-2">{tCat("products-showing", { count: products.length })}</p>
                </div>

                {/* Mobile Filter Button */}
                <div className="lg:hidden mb-4">
                    <SideFilter
                        selectedRatings={selectedRatings}
                        selectedPriceRanges={selectedPriceRanges}
                        selectedBrands={selectedBrands}
                        onRatingChange={setSelectedRatings}
                        onPriceChange={setSelectedPriceRanges}
                        onBrandChange={setSelectedBrands}
                    />
                </div>

                {/* 2-Column Layout */}
                <div className="flex flex-col lg:flex-row gap-10">
                    {/* Sidebar */}
                    <aside className="hidden lg:block lg:w-[22%] flex-shrink-0">
                        <div className="sticky top-28">
                            <SideFilter
                                selectedRatings={selectedRatings}
                                selectedPriceRanges={selectedPriceRanges}
                                selectedBrands={selectedBrands}
                                onRatingChange={setSelectedRatings}
                                onPriceChange={setSelectedPriceRanges}
                                onBrandChange={setSelectedBrands}
                            />
                        </div>
                    </aside>

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

                    {/* Main Content */}
                    <main className="flex-1 min-w-0">
                        {/* Top Bar */}
                        <div className="mb-6 flex flex-wrap items-center justify-between gap-4">
                            <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 */}
                        {error ? (
                            <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("error-loading-products")}</h3>
                                <p className="text-gray-500">{error}</p>
                            </div>
                        ) : 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>

                                {visibleCount < sortedProducts.length && (
                                    <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"
                                            onClick={handleLoadMore}
                                        >
                                            {tCat("load-more")}
                                        </button>
                                    </div>
                                )}
                            </>
                        ) : (
                            <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 || selectedPriceRanges.length > 0
                                        ? tCat("try-different-filters")
                                        : tCat("no-products-found")}
                                </p>
                            </div>
                        )}
                    </main>
                </div>
            </div>
        </div>
    );
}
