import { useState, useMemo, useCallback, useEffect } from 'react';
import { Search, X, MapPin } from 'lucide-react';
import type { Floor3DData, Position3D } from '../../lib/layoutApi';

interface SearchResult {
    type: 'plant' | 'batch' | 'strain';
    id: string;
    label: string;
    sublabel: string;
    roomName: string;
    sectionCode: string;
    sectionId: string; // For reliable section lookup
    position: {
        roomX: number;
        roomY: number;
        sectionX: number;
        sectionY: number;
        row: number;
        column: number;
        tier: number;
    };
    plant: Position3D;
}

interface PlantSearchProps {
    floorData: Floor3DData;
    onSelectResult: (result: SearchResult) => void;
    onHighlightResults: (tagNumbers: string[]) => void;
}

export function PlantSearch({ floorData, onSelectResult, onHighlightResults }: PlantSearchProps) {
    const [query, setQuery] = useState('');
    const [isOpen, setIsOpen] = useState(false);
    const [searchIndex, setSearchIndex] = useState<SearchResult[]>([]);

    // Build searchable index from floor data when it changes
    useEffect(() => {
        const results: SearchResult[] = [];

        if (!floorData?.rooms) {
            console.log('[PlantSearch] No floor data or rooms available');
            setSearchIndex([]);
            return;
        }

        for (const room of floorData.rooms) {
            for (const section of room.sections || []) {
                for (const pos of section.positions || []) {
                    if (pos.plant) {
                        results.push({
                            type: 'plant',
                            id: pos.plant.id,
                            label: pos.plant.tagNumber,
                            sublabel: `${pos.plant.strain || 'Unknown'} • ${pos.plant.stage || 'N/A'}`,
                            roomName: room.name,
                            sectionCode: section.code || section.name,
                            sectionId: section.id, // Added for reliable lookup
                            position: {
                                roomX: room.posX,
                                roomY: room.posY,
                                sectionX: section.posX,
                                sectionY: section.posY,
                                row: pos.row,
                                column: pos.column,
                                tier: pos.tier,
                            },
                            plant: pos,
                        });
                    }
                }
            }
        }

        console.log(`[PlantSearch] Built index with ${results.length} plants from ${floorData.rooms.length} rooms`);
        setSearchIndex(results);
    }, [floorData]);

    // Fuzzy search filter
    const filteredResults = useMemo(() => {
        if (!query.trim()) return [];

        const q = query.toLowerCase();
        const results = searchIndex
            .filter(r =>
                r.label.toLowerCase().includes(q) ||
                r.sublabel.toLowerCase().includes(q) ||
                r.roomName.toLowerCase().includes(q)
            )
            .slice(0, 10);

        console.log(`[PlantSearch] Query "${query}" matched ${results.length} of ${searchIndex.length} plants`);
        return results;
    }, [query, searchIndex]);

    // Update highlights when results change
    useEffect(() => {
        if (filteredResults.length > 0) {
            onHighlightResults(filteredResults.map(r => r.label));
        } else {
            onHighlightResults([]);
        }
    }, [filteredResults, onHighlightResults]);

    const handleSelect = useCallback((result: SearchResult) => {
        onSelectResult(result);
        setQuery('');
        setIsOpen(false);
    }, [onSelectResult]);

    const handleClear = useCallback(() => {
        setQuery('');
        onHighlightResults([]);
    }, [onHighlightResults]);

    return (
        <div className="relative">
            {/* Search Input */}
            <div className="flex items-center gap-2 bg-black/60 backdrop-blur rounded-lg border border-slate-700 px-3 py-2">
                <Search size={16} className="text-[var(--color-text-tertiary)]" />
                <input
                    type="text"
                    value={query}
                    onChange={(e) => {
                        setQuery(e.target.value);
                        setIsOpen(true);
                    }}
                    onFocus={() => setIsOpen(true)}
                    placeholder="Search plants, batches..."
                    className="bg-transparent text-white text-sm placeholder:text-[var(--color-text-tertiary)] outline-none flex-1 w-36"
                />
                {query && (
                    <button onClick={handleClear} className="text-[var(--color-text-tertiary)] hover:text-white">
                        <X size={14} />
                    </button>
                )}
            </div>

            {/* Results Dropdown */}
            {isOpen && filteredResults.length > 0 && (
                <div className="absolute top-full left-0 right-0 mt-1 bg-slate-900/95 backdrop-blur border border-slate-700 rounded-lg shadow-xl max-h-64 overflow-y-auto z-50">
                    {filteredResults.map((result) => (
                        <button
                            key={result.id}
                            onClick={() => handleSelect(result)}
                            className="w-full text-left px-3 py-2 hover:bg-slate-800 transition-colors flex items-start gap-3 border-b border-slate-800 last:border-0"
                        >
                            <MapPin size={14} className="text-accent mt-0.5 flex-shrink-0" />
                            <div className="flex-1 min-w-0">
                                <div className="text-white text-sm font-medium truncate">{result.label}</div>
                                <div className="text-[var(--color-text-tertiary)] text-xs truncate">{result.sublabel}</div>
                                <div className="text-[var(--color-text-tertiary)] text-[10px] mt-0.5">{result.roomName}</div>
                            </div>
                        </button>
                    ))}
                </div>
            )}

            {/* No results message */}
            {isOpen && query && filteredResults.length === 0 && (
                <div className="absolute top-full left-0 right-0 mt-1 bg-slate-900/95 backdrop-blur border border-slate-700 rounded-lg p-3 text-center">
                    <p className="text-[var(--color-text-tertiary)] text-sm">No plants found</p>
                    <p className="text-[var(--color-text-tertiary)] text-xs mt-1">Index has {searchIndex.length} plants</p>
                </div>
            )}
        </div>
    );
}
