import { useState, useEffect, useCallback, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import {
    Search,
    LayoutDashboard,
    Calendar,
    Sprout,
    Home,
    Clock,
    Package,
    BarChart3,
    Settings,
    Shield,
    LogOut,
    Command,
    Plus,
    LucideIcon
} from 'lucide-react';
import { useAuth } from '../../context/AuthContext';

interface CommandItem {
    id: string;
    label: string;
    icon: LucideIcon;
    action: () => void;
    keywords?: string[];
    section: 'navigation' | 'actions' | 'account';
}

export function CommandPalette() {
    const [isOpen, setIsOpen] = useState(false);
    const [query, setQuery] = useState('');
    const [selectedIndex, setSelectedIndex] = useState(0);
    const navigate = useNavigate();
    const { logout } = useAuth();

    const commands: CommandItem[] = useMemo(() => [
        { id: 'dashboard', label: 'Go to Dashboard', icon: LayoutDashboard, action: () => navigate('/'), section: 'navigation', keywords: ['home', 'main'] },
        { id: 'tasks', label: 'Go to Tasks', icon: Calendar, action: () => navigate('/tasks'), section: 'navigation', keywords: ['schedule', 'todo'] },
        { id: 'batches', label: 'Go to Batches', icon: Sprout, action: () => navigate('/batches'), section: 'navigation', keywords: ['plants', 'crops'] },
        { id: 'rooms', label: 'Go to Rooms', icon: Home, action: () => navigate('/rooms'), section: 'navigation', keywords: ['facility', 'zones'] },
        { id: 'timeclock', label: 'Go to Timeclock', icon: Clock, action: () => navigate('/timeclock'), section: 'navigation', keywords: ['hours', 'punch'] },
        { id: 'supplies', label: 'Go to Inventory', icon: Package, action: () => navigate('/supplies'), section: 'navigation', keywords: ['stock', 'items'] },
        { id: 'reports', label: 'Go to Reports', icon: BarChart3, action: () => navigate('/reports'), section: 'navigation', keywords: ['analytics', 'stats'] },
        { id: 'ipm', label: 'Go to IPM Dashboard', icon: Shield, action: () => navigate('/ipm'), section: 'navigation', keywords: ['pest', 'health'] },
        { id: 'settings', label: 'Go to Settings', icon: Settings, action: () => navigate('/settings'), section: 'navigation', keywords: ['preferences', 'config'] },
        { id: 'new-task', label: 'Create New Task', icon: Plus, action: () => navigate('/tasks'), section: 'actions', keywords: ['add'] },
        { id: 'log-activity', label: 'Log Touch Point', icon: Plus, action: () => navigate('/touch-points'), section: 'actions', keywords: ['water', 'feed', 'ipm'] },
        { id: 'logout', label: 'Sign Out', icon: LogOut, action: logout, section: 'account', keywords: ['exit', 'leave'] },
    ], [navigate, logout]);

    const filteredCommands = useMemo(() => {
        if (!query) return commands;
        const lowerQuery = query.toLowerCase();
        return commands.filter(cmd =>
            cmd.label.toLowerCase().includes(lowerQuery) ||
            cmd.keywords?.some(kw => kw.includes(lowerQuery))
        );
    }, [commands, query]);

    const groupedCommands = useMemo(() => {
        const groups: Record<string, CommandItem[]> = { navigation: [], actions: [], account: [] };
        filteredCommands.forEach(cmd => groups[cmd.section].push(cmd));
        return groups;
    }, [filteredCommands]);

    useEffect(() => {
        const handleKeyDown = (e: KeyboardEvent) => {
            if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
                e.preventDefault();
                setIsOpen(prev => !prev);
                setQuery('');
                setSelectedIndex(0);
            }
            if (e.key === 'Escape' && isOpen) setIsOpen(false);
            if (!isOpen) return;
            if (e.key === 'ArrowDown') {
                e.preventDefault();
                setSelectedIndex(prev => Math.min(prev + 1, filteredCommands.length - 1));
            }
            if (e.key === 'ArrowUp') {
                e.preventDefault();
                setSelectedIndex(prev => Math.max(prev - 1, 0));
            }
            if (e.key === 'Enter' && filteredCommands[selectedIndex]) {
                e.preventDefault();
                filteredCommands[selectedIndex].action();
                setIsOpen(false);
            }
        };
        window.addEventListener('keydown', handleKeyDown);
        return () => window.removeEventListener('keydown', handleKeyDown);
    }, [isOpen, filteredCommands, selectedIndex]);

    useEffect(() => { setSelectedIndex(0); }, [query]);

    if (!isOpen) return null;

    let flatIndex = -1;

    return (
        <div className="fixed inset-0 z-[100] flex items-start justify-center pt-[15vh] p-4">
            <div className="absolute inset-0 bg-black/50 backdrop-blur-sm" onClick={() => setIsOpen(false)} />
            <div className="relative w-full max-w-lg bg-[var(--color-bg-elevated)] rounded-2xl shadow-2xl overflow-hidden animate-scale-in">
                <div className="flex items-center gap-3 p-4 border-b border-[var(--color-border-default)]">
                    <Search size={20} className="text-[var(--color-text-tertiary)]" />
                    <input
                        type="text"
                        placeholder="Type a command or search..."
                        value={query}
                        onChange={(e) => setQuery(e.target.value)}
                        className="flex-1 bg-transparent text-[var(--color-text-primary)] placeholder-slate-400 outline-none text-lg"
                        autoFocus
                    />
                    <kbd className="hidden sm:inline-flex px-2 py-1 text-xs font-mono bg-[var(--color-bg-tertiary)] text-[var(--color-text-tertiary)] rounded">ESC</kbd>
                </div>
                <div className="max-h-80 overflow-y-auto p-2">
                    {filteredCommands.length === 0 ? (
                        <p className="text-center text-[var(--color-text-tertiary)] py-8">No commands found</p>
                    ) : (
                        <>
                            {groupedCommands.navigation.length > 0 && (
                                <div className="mb-2">
                                    <p className="px-3 py-1 text-xs font-medium text-[var(--color-text-tertiary)] uppercase">Navigation</p>
                                    {groupedCommands.navigation.map(cmd => {
                                        flatIndex++;
                                        const isSelected = flatIndex === selectedIndex;
                                        const Icon = cmd.icon;
                                        return (
                                            <button
                                                key={cmd.id}
                                                onClick={() => { cmd.action(); setIsOpen(false); }}
                                                className={`w-full flex items-center gap-3 px-3 py-2 rounded-lg text-left transition-colors ${isSelected ? 'bg-emerald-50 dark:bg-emerald-900/30 text-emerald-700 dark:text-emerald-300' : 'text-[var(--color-text-secondary)] hover:bg-slate-100 dark:hover:bg-slate-700'}`}
                                            >
                                                <Icon size={18} />
                                                <span>{cmd.label}</span>
                                            </button>
                                        );
                                    })}
                                </div>
                            )}
                            {groupedCommands.actions.length > 0 && (
                                <div className="mb-2">
                                    <p className="px-3 py-1 text-xs font-medium text-[var(--color-text-tertiary)] uppercase">Actions</p>
                                    {groupedCommands.actions.map(cmd => {
                                        flatIndex++;
                                        const isSelected = flatIndex === selectedIndex;
                                        const Icon = cmd.icon;
                                        return (
                                            <button
                                                key={cmd.id}
                                                onClick={() => { cmd.action(); setIsOpen(false); }}
                                                className={`w-full flex items-center gap-3 px-3 py-2 rounded-lg text-left transition-colors ${isSelected ? 'bg-emerald-50 dark:bg-emerald-900/30 text-emerald-700 dark:text-emerald-300' : 'text-[var(--color-text-secondary)] hover:bg-slate-100 dark:hover:bg-slate-700'}`}
                                            >
                                                <Icon size={18} />
                                                <span>{cmd.label}</span>
                                            </button>
                                        );
                                    })}
                                </div>
                            )}
                            {groupedCommands.account.length > 0 && (
                                <div>
                                    <p className="px-3 py-1 text-xs font-medium text-[var(--color-text-tertiary)] uppercase">Account</p>
                                    {groupedCommands.account.map(cmd => {
                                        flatIndex++;
                                        const isSelected = flatIndex === selectedIndex;
                                        const Icon = cmd.icon;
                                        return (
                                            <button
                                                key={cmd.id}
                                                onClick={() => { cmd.action(); setIsOpen(false); }}
                                                className={`w-full flex items-center gap-3 px-3 py-2 rounded-lg text-left transition-colors ${isSelected ? 'bg-red-50 dark:bg-red-900/30 text-red-700 dark:text-red-300' : 'text-[var(--color-text-secondary)] hover:bg-slate-100 dark:hover:bg-slate-700'}`}
                                            >
                                                <Icon size={18} />
                                                <span>{cmd.label}</span>
                                            </button>
                                        );
                                    })}
                                </div>
                            )}
                        </>
                    )}
                </div>
                <div className="border-t border-[var(--color-border-default)] p-3 flex items-center justify-between text-xs text-[var(--color-text-tertiary)]">
                    <div className="flex items-center gap-4">
                        <span className="flex items-center gap-1">
                            <kbd className="px-1.5 py-0.5 bg-[var(--color-bg-tertiary)] rounded">↑</kbd>
                            <kbd className="px-1.5 py-0.5 bg-[var(--color-bg-tertiary)] rounded">↓</kbd>
                            to navigate
                        </span>
                        <span className="flex items-center gap-1">
                            <kbd className="px-1.5 py-0.5 bg-[var(--color-bg-tertiary)] rounded">↵</kbd>
                            to select
                        </span>
                    </div>
                    <div className="flex items-center gap-1">
                        <Command size={12} />
                        <span>K</span>
                    </div>
                </div>
            </div>
        </div>
    );
}
