import { useState, useMemo } from 'react';
import { ChevronDown, ChevronRight, Leaf, Users, Layers } from 'lucide-react';
import type { Floor3DData, Position3D } from '../../lib/layoutApi';

interface PlantLibraryProps {
    floorData: Floor3DData;
    onPlantSelect: (plant: Position3D, roomName: string, sectionCode: string) => void;
}

type GroupBy = 'room' | 'strain' | 'stage';

export function PlantLibrary({ floorData, onPlantSelect }: PlantLibraryProps) {
    const [groupBy, setGroupBy] = useState<GroupBy>('room');
    const [expanded, setExpanded] = useState<Set<string>>(new Set());

    // Build plant list with metadata
    const allPlants = useMemo(() => {
        const plants: Array<{
            plant: Position3D;
            roomName: string;
            sectionCode: string;
            strain: string;
            stage: string;
        }> = [];

        for (const room of floorData.rooms) {
            for (const section of room.sections || []) {
                for (const pos of section.positions || []) {
                    if (pos.plant) {
                        plants.push({
                            plant: pos,
                            roomName: room.name,
                            sectionCode: section.code || section.name,
                            strain: pos.plant.strain || 'Unknown',
                            stage: pos.plant.stage || 'Unknown',
                        });
                    }
                }
            }
        }
        return plants;
    }, [floorData]);

    // Group plants by selected criteria
    const grouped = useMemo(() => {
        const groups: Record<string, typeof allPlants> = {};

        for (const item of allPlants) {
            const key = groupBy === 'room' ? item.roomName
                : groupBy === 'strain' ? item.strain
                    : item.stage;
            if (!groups[key]) groups[key] = [];
            groups[key].push(item);
        }

        // Sort groups by name, then by count
        return Object.entries(groups)
            .sort((a, b) => b[1].length - a[1].length);
    }, [allPlants, groupBy]);

    const toggleExpand = (key: string) => {
        setExpanded(prev => {
            const next = new Set(prev);
            if (next.has(key)) next.delete(key);
            else next.add(key);
            return next;
        });
    };

    const stageColor = (stage: string) => {
        switch (stage.toUpperCase()) {
            case 'VEGETATIVE': return 'text-green-400';
            case 'FLOWERING': return 'text-purple-400';
            case 'DRYING': return 'text-orange-400';
            case 'CURING': return 'text-amber-600';
            default: return 'text-[var(--color-text-tertiary)]';
        }
    };

    return (
        <div className="bg-slate-900/95 backdrop-blur border border-slate-700 rounded-lg overflow-hidden">
            {/* Header with group toggle */}
            <div className="p-3 border-b border-slate-700 flex items-center justify-between">
                <span className="text-sm font-medium text-white flex items-center gap-2">
                    <Leaf size={14} className="text-green-400" />
                    Plants ({allPlants.length})
                </span>
                <div className="flex gap-1">
                    <button
                        onClick={() => setGroupBy('room')}
                        className={`text-xs px-2 py-1 rounded ${groupBy === 'room' ? 'bg-blue-600 text-white' : 'text-[var(--color-text-tertiary)] hover:bg-slate-700'}`}
                        title="Group by Room"
                    >
                        <Layers size={12} />
                    </button>
                    <button
                        onClick={() => setGroupBy('strain')}
                        className={`text-xs px-2 py-1 rounded ${groupBy === 'strain' ? 'bg-blue-600 text-white' : 'text-[var(--color-text-tertiary)] hover:bg-slate-700'}`}
                        title="Group by Strain"
                    >
                        🌿
                    </button>
                    <button
                        onClick={() => setGroupBy('stage')}
                        className={`text-xs px-2 py-1 rounded ${groupBy === 'stage' ? 'bg-blue-600 text-white' : 'text-[var(--color-text-tertiary)] hover:bg-slate-700'}`}
                        title="Group by Stage"
                    >
                        <Users size={12} />
                    </button>
                </div>
            </div>

            {/* Groups list */}
            <div className="max-h-[400px] overflow-y-auto">
                {grouped.map(([groupName, plants]) => (
                    <div key={groupName} className="border-b border-slate-800 last:border-0">
                        {/* Group header */}
                        <button
                            onClick={() => toggleExpand(groupName)}
                            className="w-full px-3 py-2 flex items-center justify-between hover:bg-slate-800 transition-colors"
                        >
                            <span className="flex items-center gap-2 text-sm">
                                {expanded.has(groupName) ? <ChevronDown size={14} /> : <ChevronRight size={14} />}
                                <span className={groupBy === 'stage' ? stageColor(groupName) : 'text-slate-200'}>
                                    {groupName}
                                </span>
                            </span>
                            <span className="text-xs text-[var(--color-text-tertiary)] bg-slate-800 px-2 py-0.5 rounded-full">
                                {plants.length}
                            </span>
                        </button>

                        {/* Expanded plant list */}
                        {expanded.has(groupName) && (
                            <div className="bg-black/30 px-2 pb-2">
                                {plants.slice(0, 20).map((item) => (
                                    <button
                                        key={item.plant.id}
                                        onClick={() => onPlantSelect(item.plant, item.roomName, item.sectionCode)}
                                        className="w-full text-left px-2 py-1.5 hover:bg-slate-700 rounded text-xs flex justify-between items-center"
                                    >
                                        <span className="text-cyan-400 font-mono truncate max-w-[120px]">
                                            {item.plant.plant?.tagNumber}
                                        </span>
                                        <span className={`${stageColor(item.stage)} text-[10px]`}>
                                            {item.stage.substring(0, 4)}
                                        </span>
                                    </button>
                                ))}
                                {plants.length > 20 && (
                                    <div className="text-center text-[10px] text-[var(--color-text-tertiary)] py-1">
                                        +{plants.length - 20} more
                                    </div>
                                )}
                            </div>
                        )}
                    </div>
                ))}
            </div>
        </div>
    );
}
