/**
 * TypeLibrary - Sidebar component displaying plant types for drag-and-drop
 * Inspired by Rackula's device panel
 */

import { useState, useMemo } from 'react';
import { Flower2, Leaf, Scissors, Crown, Sprout, ChevronDown, GripVertical } from 'lucide-react';
import { cn } from '../../lib/utils';
import type { LayoutPlantType } from '../../lib/layoutApi';

interface TypeLibraryProps {
    plantTypes: LayoutPlantType[];
    onDragStart: (plantType: LayoutPlantType) => void;
    onCreateType?: () => void;
    className?: string;
}

const CATEGORY_LABELS: Record<string, { label: string, Icon: any }> = {
    FLOWER: { label: 'Flower', Icon: Flower2 },
    VEG: { label: 'Veg', Icon: Leaf },
    CLONE: { label: 'Clone', Icon: Scissors },
    MOTHER: { label: 'Mother', Icon: Crown },
    SEEDLING: { label: 'Seedling', Icon: Sprout },
};

const CATEGORY_ORDER = ['FLOWER', 'VEG', 'CLONE', 'MOTHER', 'SEEDLING'];

export function TypeLibrary({ plantTypes, onDragStart, onCreateType, className }: TypeLibraryProps) {
    const [search, setSearch] = useState('');
    const [expandedCategories, setExpandedCategories] = useState<Set<string>>(new Set(['FLOWER']));

    // Group by category and filter by search
    const groupedTypes = useMemo(() => {
        const filtered = plantTypes.filter(pt =>
            pt.name.toLowerCase().includes(search.toLowerCase()) ||
            pt.strain?.toLowerCase().includes(search.toLowerCase())
        );

        const groups: Record<string, LayoutPlantType[]> = {};
        for (const pt of filtered) {
            if (!groups[pt.category]) groups[pt.category] = [];
            groups[pt.category].push(pt);
        }

        return groups;
    }, [plantTypes, search]);

    const toggleCategory = (cat: string) => {
        setExpandedCategories(prev => {
            const next = new Set(prev);
            if (next.has(cat)) next.delete(cat);
            else next.add(cat);
            return next;
        });
    };

    return (
        <div className={cn('flex flex-col h-full bg-card/50 backdrop-blur-md border-r border-border', className)}>
            {/* Header */}
            <div className="p-4 border-b border-border bg-card/30">
                <div className="flex items-center justify-between mb-3">
                    <h2 className="text-xs font-display font-bold uppercase tracking-widest text-muted-foreground">Library</h2>
                    {onCreateType && (
                        <button
                            onClick={onCreateType}
                            className="text-xs px-2 py-1 bg-primary/10 text-primary hover:bg-primary/20 rounded-md transition-colors font-medium"
                        >
                            + NEW
                        </button>
                    )}
                </div>
                <div className="relative">
                    <input
                        type="text"
                        placeholder="Search types..."
                        value={search}
                        onChange={e => setSearch(e.target.value)}
                        className="w-full px-3 py-2 text-sm bg-secondary/50 border border-border rounded-lg text-foreground placeholder-muted-foreground focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary/20 transition-all"
                    />
                </div>
            </div>

            {/* Categories */}
            <div className="flex-1 overflow-y-auto custom-scrollbar">
                {CATEGORY_ORDER.map(category => {
                    const types = groupedTypes[category] || [];
                    if (types.length === 0 && search) return null;

                    const isExpanded = expandedCategories.has(category);
                    const categoryData = CATEGORY_LABELS[category];

                    return (
                        <div key={category} className="border-b border-border/50">
                            <button
                                onClick={() => toggleCategory(category)}
                                className="w-full px-4 py-3 flex items-center justify-between text-left hover:bg-secondary/30 transition-colors group"
                            >
                                <span className="text-sm font-medium text-foreground flex items-center gap-2.5">
                                    {categoryData ? (
                                        <div className="p-1 rounded bg-secondary text-primary group-hover:text-primary-hover transition-colors">
                                            <categoryData.Icon className="w-3.5 h-3.5" />
                                        </div>
                                    ) : null}
                                    {categoryData?.label || category}
                                    <span className="text-xs text-muted-foreground font-normal">({types.length})</span>
                                </span>
                                <ChevronDown className={cn('w-4 h-4 text-muted-foreground transition-transform duration-200', isExpanded && 'rotate-180')} />
                            </button>

                            {isExpanded && (
                                <div className="pb-3 px-2 space-y-1">
                                    {types.map(pt => (
                                        <PlantTypeCard key={pt.slug} plantType={pt} onDragStart={onDragStart} />
                                    ))}
                                    {types.length === 0 && (
                                        <p className="px-4 py-2 text-xs text-muted-foreground italic">No types available</p>
                                    )}
                                </div>
                            )}
                        </div>
                    );
                })}
            </div>

            {/* Footer hint */}
            <div className="p-3 border-t border-border bg-card/30 backdrop-blur-sm">
                <p className="text-[10px] uppercase tracking-wider text-muted-foreground text-center font-medium">
                    Drag to place
                </p>
            </div>
        </div>
    );
}

interface PlantTypeCardProps {
    plantType: LayoutPlantType;
    onDragStart: (plantType: LayoutPlantType) => void;
}

function PlantTypeCard({ plantType, onDragStart }: PlantTypeCardProps) {
    const handleDragStart = (e: React.DragEvent) => {
        e.dataTransfer.setData('application/json', JSON.stringify({ ...plantType, type: 'PLANT_TYPE' }));
        e.dataTransfer.effectAllowed = 'copy';
        onDragStart(plantType);
    };

    return (
        <div
            draggable
            onDragStart={handleDragStart}
            className="mx-1 mb-1 px-3 py-2.5 bg-card border border-transparent hover:border-primary/50 hover:shadow-[0_0_15px_-3px_rgba(37,99,235,0.2)] rounded-lg cursor-grab active:cursor-grabbing transition-all duration-200 group relative overflow-hidden"
        >
            <div className="flex items-center gap-3 relative z-10">
                {/* Color indicator */}
                <div
                    className="w-2.5 h-2.5 rounded-full flex-shrink-0 ring-1 ring-white/10"
                    style={{ backgroundColor: plantType.colour }}
                />

                <div className="flex-1 min-w-0">
                    <p className="text-sm font-medium text-foreground truncate">{plantType.name}</p>
                    {plantType.strain && (
                        <p className="text-[11px] text-muted-foreground truncate font-mono">{plantType.strain}</p>
                    )}
                </div>

                {/* Drag handle hint */}
                <GripVertical className="w-4 h-4 text-muted-foreground/30 opacity-0 group-hover:opacity-100 transition-opacity" />
            </div>

            {/* Quick stats */}
            {(plantType.growthDays || plantType.yieldGrams) && (
                <div className="mt-2 flex gap-3 text-[10px] text-muted-foreground border-t border-border/50 pt-1.5">
                    {plantType.growthDays && <span>{plantType.growthDays}d</span>}
                    {plantType.yieldGrams && <span>{plantType.yieldGrams}g</span>}
                </div>
            )}
        </div>
    );
}
