"use client";

import { useState } from 'react';
import { X, ChevronDown, ChevronUp, Filter, Check } from 'lucide-react';

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

interface FilterSidebarProps {
    filters: {
        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 };
    };
    activeFilters: {
        minPrice: string;
        maxPrice: string;
        brands: string[];
        conditions: string[];
        materials: string[];
        colors: string[];
        categoryId: string;
    };
    onFilterChange: (newFilters: Record<string, string | string[]>) => void;
    isOpen: boolean;
    onClose: () => void;
}

const CONDITION_MAP: Record<string, string> = {
    'New': 'Ny',
    'Excellent': 'Utmärkt',
    'Good': 'Bra',
    'Fair': 'Okej',
    'Poor': 'Sliten',
    'new': 'Ny',
    'excellent': 'Utmärkt',
    'good': 'Bra',
    'fair': 'Okej',
    'poor': 'Sliten'
};

const COLOR_MAP: Record<string, string> = {
    'Black': 'Svart',
    'White': 'Vit',
    'Red': 'Röd',
    'Blue': 'Blå',
    'Green': 'Grön',
    'Yellow': 'Gul',
    'Brown': 'Brun',
    'Grey': 'Grå',
    'Beige': 'Beige',
    'Orange': 'Orange',
    'Purple': 'Lila',
    'Pink': 'Rosa',
    'Gold': 'Guld',
    'Silver': 'Silver',
    'Multicolor': 'Flerfärgad'
};

const MATERIAL_MAP: Record<string, string> = {
    'Wood': 'Trä',
    'Metal': 'Metall',
    'Glass': 'Glas',
    'Plastic': 'Plast',
    'Fabric': 'Tyg',
    'Leather': 'Läder',
    'Stone': 'Sten',
    'Ceramic': 'Keramik'
};

export default function FilterSidebar({ filters, activeFilters, onFilterChange, isOpen, onClose }: FilterSidebarProps) {
    const [expandedSections, setExpandedSections] = useState<Record<string, boolean>>({
        categories: true,
        price: true,
        brands: true,
        condition: true,
        materials: false,
        colors: false
    });

    const toggleSection = (section: string) => {
        setExpandedSections(prev => ({ ...prev, [section]: !prev[section] }));
    };

    const handleCheckboxChange = (group: keyof typeof activeFilters, value: string) => {
        const current = (activeFilters[group] as string[]) || [];
        const newValues = current.includes(value)
            ? current.filter((item: string) => item !== value)
            : [...current, value];

        onFilterChange({ [group]: newValues });
    };

    const handlePriceChange = (type: 'minPrice' | 'maxPrice', value: string) => {
        onFilterChange({ [type]: value });
    };

    return (
        <>
            {/* Mobile Overlay */}
            {isOpen && (
                <div
                    className="fixed inset-0 bg-black/50 z-40 lg:hidden"
                    onClick={onClose}
                />
            )}

            {/* Sidebar */}
            <aside
                className={`
                    fixed left-0 w-[280px] bg-[var(--card-bg)] border-r border-[var(--border-color)] z-50 overflow-y-auto transition-transform duration-300 ease-in-out
                    lg:translate-x-0 lg:static lg:h-auto lg:w-64 lg:border-none lg:bg-transparent lg:z-0
                    ${isOpen ? 'translate-x-0' : '-translate-x-full'}
                `}
                style={{ top: '90px', height: 'calc(100% - 90px)' }}
            >
                <div className="p-5 flex items-center justify-between lg:hidden border-b border-[var(--border-color)]">
                    <h2 className="font-bold text-lg flex items-center gap-2">
                        <Filter size={18} /> Filter
                    </h2>
                    <button onClick={onClose} className="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-full">
                        <X size={20} />
                    </button>
                </div>

                <div className="p-5 space-y-8">
                    {/* Categories */}
                    <div className="filter-section">
                        <h3 className="font-bold mb-3">Kategorier</h3>
                        <div className="space-y-1 pl-1">
                            <button
                                onClick={() => onFilterChange({ categoryId: '' })}
                                className={`text-sm w-full text-left py-1.5 px-2 rounded transition-colors ${!activeFilters.categoryId ? 'font-bold bg-blue-600 !text-white' : 'text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-800'}`}
                            >
                                Alla produkter
                            </button>
                            {filters.categories.map(cat => (
                                <div key={cat.id}>
                                    <button
                                        onClick={() => onFilterChange({ categoryId: cat.id.toString() })}
                                        className={`text-sm w-full text-left py-1.5 px-2 rounded transition-colors ${activeFilters.categoryId === cat.id.toString() ? 'font-bold bg-blue-600 !text-white' : 'text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-800'}`}
                                    >
                                        {cat.name}
                                    </button>
                                    {/* Simple 1-level nesting display */}
                                    {cat.children && cat.children.length > 0 && (
                                        <div className="ml-4 mt-1 border-l-2 border-gray-100 dark:border-gray-800 pl-2">
                                            {cat.children.map(child => (
                                                <button
                                                    key={child.id}
                                                    onClick={() => onFilterChange({ categoryId: child.id.toString() })}
                                                    className={`text-sm w-full text-left py-1.5 px-2 block rounded transition-colors ${activeFilters.categoryId === child.id.toString() ? 'font-bold bg-blue-600 !text-white' : 'text-gray-500 hover:bg-gray-100 dark:hover:bg-gray-800'}`}
                                                >
                                                    {child.name}
                                                </button>
                                            ))}
                                        </div>
                                    )}
                                </div>
                            ))}
                        </div>
                    </div>

                    {/* Price Range */}
                    <div className="filter-section">
                        <div className="flex items-center justify-between mb-3 cursor-pointer" onClick={() => toggleSection('price')}>
                            <h3 className="font-bold">Pris</h3>
                            {expandedSections.price ? <ChevronUp size={16} /> : <ChevronDown size={16} />}
                        </div>
                        {expandedSections.price && (
                            <div className="space-y-3">
                                <div className="flex items-center gap-2">
                                    <input
                                        type="number"
                                        placeholder="Min"
                                        style={{
                                            flex: 1,
                                            minWidth: 0,
                                            padding: '0.5rem',
                                            border: '1px solid var(--border-color)',
                                            background: 'var(--card-bg)',
                                            color: 'var(--text-color)',
                                            fontSize: '0.875rem'
                                        }}
                                        value={activeFilters.minPrice}
                                        onChange={(e) => handlePriceChange('minPrice', e.target.value)}
                                    />
                                    <span>-</span>
                                    <input
                                        type="number"
                                        placeholder="Max"
                                        style={{
                                            flex: 1,
                                            minWidth: 0,
                                            padding: '0.5rem',
                                            border: '1px solid var(--border-color)',
                                            background: 'var(--card-bg)',
                                            color: 'var(--text-color)',
                                            fontSize: '0.875rem'
                                        }}
                                        value={activeFilters.maxPrice}
                                        onChange={(e) => handlePriceChange('maxPrice', e.target.value)}
                                    />
                                </div>
                            </div>
                        )}
                    </div>

                    {/* Conditions */}
                    <div className="filter-section">
                        <div className="flex items-center justify-between mb-3 cursor-pointer" onClick={() => toggleSection('condition')}>
                            <h3 className="font-bold">Skick</h3>
                            {expandedSections.condition ? <ChevronUp size={16} /> : <ChevronDown size={16} />}
                        </div>
                        {expandedSections.condition && (
                            <div className="space-y-2">
                                {filters.conditions.map((item) => (
                                    <label key={item.product_condition} className="flex items-center gap-2 cursor-pointer text-sm">
                                        <div className={`w-4 h-4 rounded border flex items-center justify-center transition-colors ${activeFilters.conditions.includes(item.product_condition) ? 'bg-[var(--text-color)] border-[var(--text-color)] text-[var(--background)]' : 'border-[var(--border-color)]'}`}>
                                            {activeFilters.conditions.includes(item.product_condition) && <Check size={12} />}
                                        </div>
                                        <input
                                            type="checkbox"
                                            className="hidden"
                                            checked={activeFilters.conditions.includes(item.product_condition)}
                                            onChange={() => handleCheckboxChange('conditions', item.product_condition)}
                                        />
                                        <span className="flex-grow">{CONDITION_MAP[item.product_condition] || item.product_condition}</span>
                                        <span className="text-xs text-gray-400">({item.count})</span>
                                    </label>
                                ))}
                            </div>
                        )}
                    </div>

                    {/* Brands */}
                    <div className="filter-section">
                        <div className="flex items-center justify-between mb-3 cursor-pointer" onClick={() => toggleSection('brands')}>
                            <h3 className="font-bold">Märke</h3>
                            {expandedSections.brands ? <ChevronUp size={16} /> : <ChevronDown size={16} />}
                        </div>
                        {expandedSections.brands && (
                            <div className="space-y-2 max-h-48 overflow-y-auto scrollbar-thin">
                                {filters.brands.map((item) => (
                                    <label key={item.brand} className="flex items-center gap-2 cursor-pointer text-sm">
                                        <div className={`w-4 h-4 rounded border flex items-center justify-center transition-colors ${activeFilters.brands.includes(item.brand) ? 'bg-[var(--text-color)] border-[var(--text-color)] text-[var(--background)]' : 'border-[var(--border-color)]'}`}>
                                            {activeFilters.brands.includes(item.brand) && <Check size={12} />}
                                        </div>
                                        <input
                                            type="checkbox"
                                            className="hidden"
                                            checked={activeFilters.brands.includes(item.brand)}
                                            onChange={() => handleCheckboxChange('brands', item.brand)}
                                        />
                                        <span className="flex-grow truncate">{item.brand}</span>
                                        <span className="text-xs text-gray-400">({item.count})</span>
                                    </label>
                                ))}
                            </div>
                        )}
                    </div>

                    {/* Colors */}
                    <div className="filter-section">
                        <div className="flex items-center justify-between mb-3 cursor-pointer" onClick={() => toggleSection('colors')}>
                            <h3 className="font-bold">Färg</h3>
                            {expandedSections.colors ? <ChevronUp size={16} /> : <ChevronDown size={16} />}
                        </div>
                        {expandedSections.colors && (
                            <div className="flex flex-wrap gap-2">
                                {filters.colors.map((item) => {
                                    // Helper for basic color mapping, otherwise use generic circle
                                    // A robust app would have a color map.
                                    return (
                                        <button
                                            key={item.color}
                                            onClick={() => handleCheckboxChange('colors', item.color)}
                                            title={`${item.color} (${item.count})`}
                                            className={`
                                                w-8 h-8 rounded-full border-2 flex items-center justify-center transition-all
                                                ${activeFilters.colors.includes(item.color) ? 'border-[var(--primary-color)] scale-110' : 'border-transparent hover:border-gray-300'}
                                            `}
                                            style={{ backgroundColor: item.color.toLowerCase() === 'custom' ? '#eee' : item.color.toLowerCase() }}
                                        >
                                            {activeFilters.colors.includes(item.color) && <Check size={14} className={['white', 'yellow', 'beige', 'cream', 'ivory'].includes(item.color.toLowerCase()) ? 'text-black' : 'text-white'} />}
                                        </button>
                                    );
                                })}
                            </div>
                        )}
                    </div>

                    <button
                        onClick={() => onFilterChange({
                            minPrice: '', maxPrice: '', brands: [], conditions: [], materials: [], colors: [], categoryId: ''
                        })}
                        className="w-full py-2 text-sm text-gray-500 hover:text-black dark:hover:text-white border border-gray-200 dark:border-gray-700 rounded transition-colors"
                    >
                        Rensa filter
                    </button>
                </div>
            </aside>
        </>
    );
}
