"use client";

import { useState, useEffect } from 'react';
import { useSearchParams, useRouter } from 'next/navigation';
import ProductCard from '@/components/products/ProductCard';
import FilterSidebar from '@/components/products/FilterSidebar';
import { SlidersHorizontal } from 'lucide-react';
import '@/styles/Products.css';

interface Product {
    id: number;
    name: string;
    description: string;
    price: number;
    original_price?: number;
    images: string[];
    primary_image?: string;
    stock_status: 'in_stock' | 'out_of_stock';
    product_condition: string;
    badge_text?: string;
    badge_color?: string;
    brand?: string;
    material?: string;
    color?: string;
    created_at?: string;
    category_names?: string[];
}

interface CategoryNode {
    id: number;
    name: string;
    children: CategoryNode[];
}

interface ProductCatalogProps {
    initialCategoryId?: string;
    initialCategoryName?: string;
}

export default function ProductCatalog({ initialCategoryId, initialCategoryName }: ProductCatalogProps) {
    const searchParams = useSearchParams();
    const router = useRouter();

    const [products, setProducts] = useState<Product[]>([]);
    const [loading, setLoading] = useState(true);
    const [filterData, setFilterData] = useState<{
        categories: CategoryNode[];
        brands: { brand: string; count: number }[];
        materials: { material: string; count: number }[];
        conditions: { product_condition: string; count: number }[];
        colors: { color: string; count: number }[];
        priceRange: { min: number; max: number };
    }>({
        categories: [],
        brands: [],
        materials: [],
        conditions: [],
        colors: [],
        priceRange: { min: 0, max: 100000 }
    });
    const [total, setTotal] = useState(0);
    const [showFilters, setShowFilters] = useState(false);

    const activeFilters = {
        q: searchParams.get('q') || '',
        page: searchParams.get('page') || '1',
        sort: searchParams.get('sort') || 'newest',
        minPrice: searchParams.get('minPrice') || '',
        maxPrice: searchParams.get('maxPrice') || '',
        brands: searchParams.get('brands') ? searchParams.get('brands')!.split(',') : [],
        conditions: searchParams.get('conditions') ? searchParams.get('conditions')!.split(',') : [],
        materials: searchParams.get('materials') ? searchParams.get('materials')!.split(',') : [],
        colors: searchParams.get('colors') ? searchParams.get('colors')!.split(',') : [],
        categoryId: initialCategoryId || searchParams.get('category_id') || ''
    };

    useEffect(() => {
        const fetchFilters = async () => {
            try {
                const res = await fetch('/api/filters');
                if (res.ok) {
                    const data = await res.json();
                    setFilterData(data);
                }
            } catch (error) {
                console.error('Failed to load filters', error);
            }
        };
        fetchFilters();
    }, []);

    useEffect(() => {
        const fetchProducts = async () => {
            setLoading(true);
            try {
                const params = new URLSearchParams(searchParams.toString());
                if (initialCategoryId) {
                    params.set('category_id', initialCategoryId);
                }
                const res = await fetch(`/api/products?${params.toString()}`);
                if (res.ok) {
                    const data = await res.json();
                    setProducts(data.products);
                    setTotal(data.pagination.total);
                }
            } catch (error) {
                console.error('Failed to load products', error);
            } finally {
                setLoading(false);
            }
        };
        fetchProducts();
    }, [searchParams, initialCategoryId]);

    const updateFilters = (newFilters: Record<string, string | string[]>) => {
        const params = new URLSearchParams(searchParams.toString());

        // Handle category clearing/changing separately due to URL structure if needed, 
        // but here we can just integrate it into the main loop by mapping keys.

        Object.entries(newFilters).forEach(([key, value]) => {
            let actualKey = key;
            if (key === 'categoryId') {
                actualKey = 'category_id';
                params.delete('slug'); // Clear slug if category changes
            }

            if (key === 'categoryId' && initialCategoryId && value !== '') return;

            if (Array.isArray(value)) {
                if (value.length > 0) {
                    params.set(actualKey, value.join(','));
                } else {
                    params.delete(actualKey);
                }
            } else if (value) {
                params.set(actualKey, value as string);
            } else {
                params.delete(actualKey);
            }
        });

        // If category_id was truly cleared in newFilters, we might need to handle the path
        if (newFilters.categoryId === '' && !initialCategoryId) {
            router.push(`/products?${params.toString()}`);
        } else {
            params.set('page', '1'); // Reset to page 1 on filter change
            router.push(`?${params.toString()}`);
        }
    };

    const totalPages = Math.ceil(total / 12);

    return (
        <div className="products-container">
            {/* Header */}
            <div className="products-header">
                <div>
                    <h1>
                        {initialCategoryName || (activeFilters.q ? `Resultat för "${activeFilters.q}"` : 'Alla Produkter')}
                    </h1>
                    <p className="products-count">
                        Visar {products.length} av {total} produkter
                    </p>
                </div>

                <div className="products-header-actions">
                    <button
                        className="products-btn filter-mobile-btn lg:hidden"
                        onClick={() => setShowFilters(true)}
                    >
                        <SlidersHorizontal size={16} />
                        Filter
                    </button>

                    <select
                        className="products-select"
                        value={activeFilters.sort}
                        onChange={(e) => updateFilters({ sort: e.target.value })}
                        aria-label="Sortera produkter"
                    >
                        <option value="newest">Nyast först</option>
                        <option value="price_asc">Lägsta pris</option>
                        <option value="price_desc">Högsta pris</option>
                        <option value="name_asc">Namn (A-Ö)</option>
                        <option value="name_desc">Namn (Ö-A)</option>
                        <option value="popular">Mest populära</option>
                    </select>
                </div>
            </div>

            <div className="products-layout">
                <FilterSidebar
                    filters={filterData}
                    activeFilters={activeFilters}
                    onFilterChange={updateFilters}
                    isOpen={showFilters}
                    onClose={() => setShowFilters(false)}
                />

                <div style={{ flexGrow: 1 }}>
                    {loading ? (
                        <div className="products-grid">
                            {[1, 2, 3, 4, 5, 6, 7, 8].map((n) => (
                                <div key={n} className="product-skeleton" />
                            ))}
                        </div>
                    ) : products.length > 0 ? (
                        <>
                            <div className="products-grid">
                                {products.map((product) => (
                                    <ProductCard key={product.id} product={product} />
                                ))}
                            </div>

                            {totalPages > 1 && (
                                <div className="products-pagination">
                                    {Array.from({ length: totalPages }).map((_, i) => (
                                        <button
                                            key={i}
                                            onClick={() => updateFilters({ page: (i + 1).toString() })}
                                            className={`pagination-btn ${parseInt(activeFilters.page) === i + 1 ? 'active' : ''}`}
                                        >
                                            {i + 1}
                                        </button>
                                    ))}
                                </div>
                            )}
                        </>
                    ) : (
                        <div className="products-empty">
                            <h3>Inga produkter hittades</h3>
                            <p>Prova att justera dina filter eller sök efter något annat.</p>
                            <button
                                onClick={() => router.push('/products')}
                                className="products-btn primary"
                            >
                                Rensa alla filter
                            </button>
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
}
