// src/components/productPage/UserProductPage.jsx
import React, { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import axios from "axios";

import FiltersSidebar from "./FiltersSidebar";
import SortBar from "./SortBar";
import ProductGrid from "./ProductGrid";
import PaginationBar from "./PaginationBar";
import ProductSkeleton from "./ProductSkeleton";

import { Sheet, SheetContent, SheetTrigger } from "@/components/ui/sheet";
import { Button } from "@/components/ui/button";
import { Filter } from "lucide-react";

const UserProductPage = () => {
    const { slug, id } = useParams();
    const API_URL = import.meta.env.VITE_API_URL;

    const [products, setProducts] = useState([]);
    const [filtered, setFiltered] = useState([]);
    const [brands, setBrands] = useState([]);

    const [loading, setLoading] = useState(true);

    const [filters, setFilters] = useState({
        price: [0, 510000],
        brand: [],
        rating: null,
        discount: null,
        inStock: false,
        freeDelivery: false,
        newArrival: null,
        verifiedSeller: false,
    });

    const [sortBy, setSortBy] = useState("relevance");
    const [page, setPage] = useState(1);

    /* -------------------- FETCH PRODUCTS -------------------- */
    const fetchProducts = async () => {
        try {
            setLoading(true);

            const res = await axios.get(
                `${API_URL}/api/product/allproducts?category=${id}&limit=200`
            );

            const list = res.data.products || [];

            setProducts(list);
            setFiltered(list);

            const brandSet = [
                ...new Set(list.map((p) => p.brand?.trim()).filter(Boolean)),
            ];

            // SORT brands alphabetically
            setBrands(brandSet.sort());
        } catch (error) {
            console.error("Error fetching products:", error);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        if (id) fetchProducts();
    }, [id]);

    /* -------------------- APPLY FILTERS -------------------- */
    useEffect(() => {
        let data = [...products];

        // PRICE
        data = data.filter(
            (p) => p.price >= filters.price[0] && p.price <= filters.price[1]
        );

        // BRAND
        if (filters.brand.length > 0) {
            data = data.filter((p) => filters.brand.includes(p.brand));
        }

        // RATING
        if (filters.rating) {
            data = data.filter(
                (p) => Math.floor(p.rating || 4) >= Number(filters.rating)
            );
        }

        // DISCOUNT
        if (filters.discount) {
            data = data.filter((p) => {
                const d = p.strikethroughPrice
                    ? Math.round(
                        ((p.strikethroughPrice - p.price) /
                            p.strikethroughPrice) *
                        100
                    )
                    : 0;
                return d >= filters.discount;
            });
        }

        // FREE DELIVERY
        if (filters.freeDelivery) {
            data = data.filter((p) =>
                p.infoSections?.some((info) =>
                    info.title?.toLowerCase().includes("free delivery")
                )
            );
        }

        // IN STOCK
        if (filters.inStock) {
            data = data.filter((p) => p.status === "in_stock");
        }

        // NEW ARRIVAL
        if (filters.newArrival) {
            data = data.filter((p) => {
                const d = new Date(p.createdAt);
                const now = new Date();
                const diff = (now - d) / (1000 * 60 * 60 * 24);
                return diff <= filters.newArrival;
            });
        }

        // VERIFIED SELLER (placeholder; adapt if you have real data)
        if (filters.verifiedSeller) {
            data = data.filter((p) => p.brand?.toLowerCase() !== "unknown");
        }

        // SORTING
        switch (sortBy) {
            case "low-high":
                data.sort((a, b) => a.price - b.price);
                break;
            case "high-low":
                data.sort((a, b) => b.price - a.price);
                break;
            case "newest":
                data.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
                break;
            case "az":
                data.sort((a, b) => a.name.localeCompare(b.name));
                break;
            default:
                break;
        }

        setFiltered(data);
        setPage(1);
    }, [filters, sortBy, products]);

    const ITEMS_PER_PAGE = 12;
    const paginated = filtered.slice(
        (page - 1) * ITEMS_PER_PAGE,
        page * ITEMS_PER_PAGE
    );

    return (
        <div className="flex w-full min-h-screen bg-gray-50">

            {/* DESKTOP SIDEBAR */}
            <div className="hidden lg:block w-72  bg-white">
                <FiltersSidebar
                    brands={brands}
                    filters={filters}
                    setFilters={setFilters}
                />
            </div>

            {/* MAIN CONTENT */}
            <div className="flex-1 p-4 md:p-6">

                {/* MOBILE FILTER BUTTON */}
                <div className="lg:hidden mb-4">
                    <Sheet>
                        <SheetTrigger asChild>
                            <Button variant="outline" className="flex gap-2">
                                <Filter size={18} />
                                Filters
                            </Button>
                        </SheetTrigger>

                        <SheetContent side="left" className="w-72 p-0">
                            <FiltersSidebar
                                brands={brands}
                                filters={filters}
                                setFilters={setFilters}
                            />
                        </SheetContent>
                    </Sheet>
                </div>

                {/* SORTING */}
                <SortBar sortBy={sortBy} setSortBy={setSortBy} />

                {/* PRODUCT GRID */}
                {loading ? (
                    <div className="grid grid-cols-2 p-4 sm:grid-cols-3 md:grid-cols-4 gap-4">
                        {Array.from({ length: 8 }).map((_, i) => (
                            <ProductSkeleton key={i} />
                        ))}
                    </div>
                ) : filtered.length === 0 ? (
                    <div className="text-center py-20 text-gray-500 text-lg">
                        No products found.
                    </div>
                ) : (
                    <ProductGrid products={paginated} />
                )}

                {/* PAGINATION */}
                <PaginationBar
                    total={filtered.length}
                    perPage={ITEMS_PER_PAGE}
                    page={page}
                    setPage={setPage}
                />
            </div>
        </div>
    );
};

export default UserProductPage;
