'use client';

import { useState, useEffect, useRef } from 'react';
import { Combobox, Dialog, DialogBackdrop, DialogPanel } from '@headlessui/react';
import { MagnifyingGlassIcon } from '@heroicons/react/24/outline';
import { useRouter } from 'next/navigation';
import { getUser } from '@/lib/auth';
import {
    HomeIcon,
    RocketLaunchIcon,
    ChartBarIcon,
    BriefcaseIcon,
    LifebuoyIcon,
    CreditCardIcon,
    DocumentTextIcon,
    FolderIcon,
    ShareIcon,
    Cog6ToothIcon,
    PlusIcon,
    ArrowRightIcon,
    UserCircleIcon
} from '@heroicons/react/24/outline';

interface CommandPaletteProps {
    isOpen: boolean;
    setIsOpen: (isOpen: boolean) => void;
}

export default function CommandPalette({ isOpen, setIsOpen }: CommandPaletteProps) {
    const [query, setQuery] = useState('');
    const [availableSolutions, setAvailableSolutions] = useState<string[]>([]);
    const router = useRouter();
    const inputRef = useRef<HTMLInputElement>(null);

    // Buscar soluções disponíveis
    useEffect(() => {
        const fetchSolutions = async () => {
            try {
                const response = await fetch('/api/tenant/solutions', {
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`,
                    },
                });

                if (response.ok) {
                    const data = await response.json();
                    const solutions = data.solutions || [];
                    const slugs = solutions.map((s: any) => s.slug.toLowerCase());
                    setAvailableSolutions(['dashboard', ...slugs]); // Dashboard sempre disponível
                } else {
                    // Fallback: mostrar tudo
                    setAvailableSolutions(['dashboard', 'crm', 'erp', 'projetos', 'helpdesk', 'pagamentos', 'contratos', 'documentos', 'social']);
                }
            } catch (error) {
                console.error('Erro ao buscar soluções:', error);
                // Fallback: mostrar tudo
                setAvailableSolutions(['dashboard', 'crm', 'erp', 'projetos', 'helpdesk', 'pagamentos', 'contratos', 'documentos', 'social']);
            }
        };

        if (isOpen) {
            fetchSolutions();
        }
    }, [isOpen]);

    // Atalho de teclado (Ctrl+K ou Cmd+K)
    useEffect(() => {
        const onKeydown = (event: KeyboardEvent) => {
            if (event.key === 'k' && (event.metaKey || event.ctrlKey)) {
                event.preventDefault();
                setIsOpen(true);
            }
        };
        window.addEventListener('keydown', onKeydown);
        return () => {
            window.removeEventListener('keydown', onKeydown);
        };
    }, [setIsOpen]);

    const navigation = [
        // Agência
        { name: 'Visão Geral', href: '/dashboard', icon: HomeIcon, category: 'Navegação', solution: 'dashboard', allowedTypes: ['agency_user'] },
        { name: 'CRM', href: '/crm', icon: RocketLaunchIcon, category: 'Navegação', solution: 'crm', allowedTypes: ['agency_user'] },
        { name: 'ERP', href: '/erp', icon: ChartBarIcon, category: 'Navegação', solution: 'erp', allowedTypes: ['agency_user'] },
        { name: 'Projetos', href: '/projetos', icon: BriefcaseIcon, category: 'Navegação', solution: 'projetos', allowedTypes: ['agency_user'] },
        { name: 'Helpdesk', href: '/helpdesk', icon: LifebuoyIcon, category: 'Navegação', solution: 'helpdesk', allowedTypes: ['agency_user'] },
        { name: 'Pagamentos', href: '/pagamentos', icon: CreditCardIcon, category: 'Navegação', solution: 'pagamentos', allowedTypes: ['agency_user'] },
        { name: 'Contratos', href: '/contratos', icon: DocumentTextIcon, category: 'Navegação', solution: 'contratos', allowedTypes: ['agency_user'] },
        { name: 'Documentos', href: '/documentos', icon: FolderIcon, category: 'Navegação', solution: 'documentos', allowedTypes: ['agency_user'] },
        { name: 'Redes Sociais', href: '/social', icon: ShareIcon, category: 'Navegação', solution: 'social', allowedTypes: ['agency_user'] },
        { name: 'Configurações', href: '/configuracoes', icon: Cog6ToothIcon, category: 'Navegação', solution: 'dashboard', allowedTypes: ['agency_user'] },

        // Cliente
        { name: 'Dashboard', href: '/cliente/dashboard', icon: HomeIcon, category: 'Navegação', solution: 'dashboard', allowedTypes: ['customer'] },
        { name: 'Meus Leads', href: '/cliente/leads', icon: RocketLaunchIcon, category: 'Navegação', solution: 'crm', allowedTypes: ['customer'] },
        { name: 'Minhas Listas', href: '/cliente/listas', icon: FolderIcon, category: 'Navegação', solution: 'crm', allowedTypes: ['customer'] },
        { name: 'Meu Perfil', href: '/cliente/perfil', icon: UserCircleIcon, category: 'Navegação', solution: 'dashboard', allowedTypes: ['customer'] },

        // Ações Agência
        { name: 'Novo Projeto', href: '/projetos/novo', icon: PlusIcon, category: 'Ações', solution: 'projetos', allowedTypes: ['agency_user'] },
        { name: 'Novo Chamado', href: '/helpdesk/novo', icon: PlusIcon, category: 'Ações', solution: 'helpdesk', allowedTypes: ['agency_user'] },
        { name: 'Novo Contrato', href: '/contratos/novo', icon: PlusIcon, category: 'Ações', solution: 'contratos', allowedTypes: ['agency_user'] },
    ];

    // Filtrar por soluções disponíveis e tipo de usuário
    const user = getUser();
    const userType = user?.user_type || 'agency_user';

    const allowedNavigation = navigation.filter(item =>
        availableSolutions.includes(item.solution) &&
        (!item.allowedTypes || item.allowedTypes.includes(userType))
    );

    const filteredItems =
        query === ''
            ? allowedNavigation
            : allowedNavigation.filter((item) => {
                return item.name.toLowerCase().includes(query.toLowerCase());
            });

    // Agrupar itens por categoria
    const groups = filteredItems.reduce((acc, item) => {
        if (!acc[item.category]) {
            acc[item.category] = [];
        }
        acc[item.category].push(item);
        return acc;
    }, {} as Record<string, typeof filteredItems>);

    const handleSelect = (item: typeof navigation[0] | null) => {
        if (!item) return;
        setIsOpen(false);
        router.push(item.href);
        setQuery('');
    };

    return (
        <Dialog open={isOpen} onClose={setIsOpen} className="relative z-50" initialFocus={inputRef}>
            <DialogBackdrop
                transition
                className="fixed inset-0 bg-zinc-900/40 backdrop-blur-sm transition-opacity duration-300 data-[closed]:opacity-0"
            />

            <div className="fixed inset-0 z-10 overflow-y-auto p-4 sm:p-6 md:p-20">
                <DialogPanel
                    transition
                    className="mx-auto max-w-2xl transform overflow-hidden rounded-xl bg-white dark:bg-zinc-900 shadow-2xl transition-all duration-300 data-[closed]:opacity-0 data-[closed]:scale-95"
                >
                    <Combobox onChange={handleSelect}>
                        <div className="relative">
                            <MagnifyingGlassIcon
                                className="pointer-events-none absolute left-4 top-3.5 h-5 w-5 text-zinc-400"
                                aria-hidden="true"
                            />
                            <Combobox.Input
                                ref={inputRef}
                                className="h-12 w-full border-0 bg-transparent pl-11 pr-4 text-zinc-900 dark:text-white placeholder:text-zinc-400 focus:ring-0 sm:text-sm font-medium"
                                placeholder="O que você procura?"
                                onChange={(event) => setQuery(event.target.value)}
                                displayValue={(item: any) => item?.name}
                                autoComplete="off"
                            />
                        </div>

                        {filteredItems.length > 0 && (
                            <Combobox.Options static className="max-h-[60vh] scroll-py-2 overflow-y-auto py-2 text-sm text-zinc-800 dark:text-zinc-200">
                                {Object.entries(groups).map(([category, items]) => (
                                    <div key={category}>
                                        <div className="px-4 py-2 text-[10px] font-bold text-zinc-400 uppercase tracking-wider bg-zinc-50/50 dark:bg-zinc-800/50 mt-2 first:mt-0 mb-1">
                                            {category}
                                        </div>
                                        {items.map((item) => (
                                            <Combobox.Option
                                                key={item.href}
                                                value={item}
                                                className={({ active }) =>
                                                    `cursor-pointer select-none px-4 py-2.5 transition-colors ${active
                                                        ? '[background:var(--gradient)] text-white'
                                                        : ''
                                                    }`
                                                }
                                            >
                                                {({ active }) => (
                                                    <div className="flex items-center gap-3">
                                                        <div className={`flex h-8 w-8 items-center justify-center rounded-md ${active
                                                            ? 'bg-white/20 text-white'
                                                            : 'bg-zinc-50 dark:bg-zinc-900 text-zinc-400'
                                                            }`}>
                                                            <item.icon
                                                                className="h-4 w-4"
                                                                aria-hidden="true"
                                                            />
                                                        </div>
                                                        <span className={`flex-auto truncate font-medium ${active ? 'text-white' : 'text-zinc-600 dark:text-zinc-400'}`}>
                                                            {item.name}
                                                        </span>
                                                        {active && (
                                                            <ArrowRightIcon className="h-4 w-4 text-white/70" />
                                                        )}
                                                    </div>
                                                )}
                                            </Combobox.Option>
                                        ))}
                                    </div>
                                ))}
                            </Combobox.Options>
                        )}

                        {query !== '' && filteredItems.length === 0 && (
                            <div className="py-14 px-6 text-center text-sm sm:px-14">
                                <MagnifyingGlassIcon className="mx-auto h-6 w-6 text-zinc-400" aria-hidden="true" />
                                <p className="mt-4 font-semibold text-zinc-900 dark:text-white">Nenhum resultado encontrado</p>
                                <p className="mt-2 text-zinc-500">Não conseguimos encontrar nada para &quot;{query}&quot;. Tente buscar por páginas ou ações.</p>
                            </div>
                        )}

                        <div className="flex items-center justify-between px-4 py-3 bg-zinc-50 dark:bg-zinc-900/50">
                            <div className="flex gap-4 text-[10px] text-zinc-500 font-medium">
                                <span className="flex items-center gap-1.5">
                                    <kbd className="flex h-5 w-5 items-center justify-center rounded bg-white font-sans text-xs text-zinc-400 dark:bg-zinc-800">↵</kbd>
                                    Selecionar
                                </span>
                                <span className="flex items-center gap-1.5">
                                    <kbd className="flex h-5 w-5 items-center justify-center rounded bg-white font-sans text-xs text-zinc-400 dark:bg-zinc-800">↓</kbd>
                                    <kbd className="flex h-5 w-5 items-center justify-center rounded bg-white font-sans text-xs text-zinc-400 dark:bg-zinc-800">↑</kbd>
                                    Navegar
                                </span>
                            </div>
                            <div className="text-[10px] text-zinc-500 font-medium">
                                <span className="flex items-center gap-1.5">
                                    <kbd className="flex h-5 w-auto px-1.5 items-center justify-center rounded bg-white font-sans text-xs text-zinc-400 dark:bg-zinc-800">Esc</kbd>
                                    Fechar
                                </span>
                            </div>
                        </div>
                    </Combobox>
                </DialogPanel>
            </div>
        </Dialog>
    );
}
