/**
 * CommandPalette Component
 * Paleta de comandos com Ctrl+K para navegação rápida
 * @version 1.0
 */

import { useEffect, useState, useCallback, useRef } from "react";
import { useNavigate } from "react-router-dom";
import {
  Search,
  Calendar,
  Users,
  UserPlus,
  Clock,
  FileText,
  Settings,
  LogOut,
  Command,
  ArrowRight,
} from "lucide-react";
import Fuse from "fuse.js";

interface CommandAction {
  id: string;
  label: string;
  description?: string;
  icon: React.ComponentType<{ className?: string }>;
  keywords: string[];
  action: () => void;
  category: "navigation" | "action" | "search";
}

interface CommandPaletteProps {
  onClose: () => void;
}

export function CommandPalette({ onClose }: CommandPaletteProps) {
  const [search, setSearch] = useState("");
  const [selectedIndex, setSelectedIndex] = useState(0);
  const navigate = useNavigate();
  const inputRef = useRef<HTMLInputElement>(null);
  const listRef = useRef<HTMLDivElement>(null);

  // Definir todas as ações disponíveis
  const commands: CommandAction[] = [
    // Navegação
    {
      id: "nav-home",
      label: "Ir para Dashboard",
      description: "Página inicial com métricas",
      icon: Calendar,
      keywords: ["dashboard", "home", "inicio", "painel"],
      action: () => {
        navigate("/painel-medico");
        onClose();
      },
      category: "navigation",
    },
    {
      id: "nav-patients",
      label: "Ver Lista de Pacientes",
      description: "Todos os pacientes cadastrados",
      icon: Users,
      keywords: ["pacientes", "lista", "patients"],
      action: () => {
        navigate("/lista-pacientes");
        onClose();
      },
      category: "navigation",
    },
    {
      id: "nav-appointments",
      label: "Ver Consultas",
      description: "Lista de todas as consultas",
      icon: Calendar,
      keywords: ["consultas", "appointments", "agenda"],
      action: () => {
        navigate("/painel-secretaria");
        onClose();
      },
      category: "navigation",
    },
    {
      id: "nav-doctors",
      label: "Ver Médicos",
      description: "Lista de médicos",
      icon: UserPlus,
      keywords: ["medicos", "doctors", "lista"],
      action: () => {
        navigate("/lista-medicos");
        onClose();
      },
      category: "navigation",
    },
    // Ações rápidas
    {
      id: "action-new-appointment",
      label: "Nova Consulta",
      description: "Agendar nova consulta",
      icon: Calendar,
      keywords: ["nova", "consulta", "agendar", "new", "appointment"],
      action: () => {
        navigate("/painel-secretaria");
        onClose();
        // Trigger modal após navegação
        setTimeout(() => {
          const event = new Event("open-create-appointment");
          window.dispatchEvent(event);
        }, 100);
      },
      category: "action",
    },
    {
      id: "action-new-patient",
      label: "Cadastrar Paciente",
      description: "Adicionar novo paciente",
      icon: UserPlus,
      keywords: ["novo", "paciente", "cadastrar", "new", "patient"],
      action: () => {
        navigate("/lista-pacientes");
        onClose();
        // Trigger modal após navegação
        setTimeout(() => {
          const event = new Event("open-create-patient");
          window.dispatchEvent(event);
        }, 100);
      },
      category: "action",
    },
    {
      id: "search-patient",
      label: "Buscar Paciente",
      description: "Pesquisar por nome ou CPF",
      icon: Search,
      keywords: ["buscar", "paciente", "search", "find"],
      action: () => {
        navigate("/lista-pacientes");
        onClose();
      },
      category: "search",
    },
    {
      id: "nav-availability",
      label: "Gerenciar Disponibilidade",
      description: "Configurar horários disponíveis",
      icon: Clock,
      keywords: ["disponibilidade", "horarios", "availability"],
      action: () => {
        navigate("/painel-medico?tab=disponibilidade");
        onClose();
      },
      category: "navigation",
    },
    {
      id: "nav-reports",
      label: "Ver Relatórios",
      description: "Estatísticas e métricas",
      icon: FileText,
      keywords: ["relatorios", "reports", "estatisticas", "metricas"],
      action: () => {
        navigate("/painel-medico?tab=relatorios");
        onClose();
      },
      category: "navigation",
    },
    {
      id: "nav-settings",
      label: "Configurações",
      description: "Ajustes do sistema",
      icon: Settings,
      keywords: ["config", "settings", "ajustes"],
      action: () => {
        navigate("/painel-medico?tab=perfil");
        onClose();
      },
      category: "navigation",
    },
    {
      id: "action-logout",
      label: "Sair",
      description: "Fazer logout",
      icon: LogOut,
      keywords: ["sair", "logout", "exit"],
      action: () => {
        localStorage.removeItem("mediconnect_user");
        navigate("/login");
        onClose();
      },
      category: "action",
    },
  ];

  // Configurar Fuse.js para fuzzy search
  const fuse = new Fuse(commands, {
    keys: ["label", "description", "keywords"],
    threshold: 0.3,
    includeScore: true,
  });

  // Filtrar comandos baseado na busca
  const filteredCommands = search.trim()
    ? fuse.search(search).map((result) => result.item)
    : commands;

  // Navegar com teclado
  const handleKeyDown = useCallback(
    (e: KeyboardEvent) => {
      if (e.key === "Escape") {
        onClose();
      } else if (e.key === "ArrowDown") {
        e.preventDefault();
        setSelectedIndex((prev) =>
          prev < filteredCommands.length - 1 ? prev + 1 : 0
        );
      } else if (e.key === "ArrowUp") {
        e.preventDefault();
        setSelectedIndex((prev) =>
          prev > 0 ? prev - 1 : filteredCommands.length - 1
        );
      } else if (e.key === "Enter") {
        e.preventDefault();
        if (filteredCommands[selectedIndex]) {
          filteredCommands[selectedIndex].action();
        }
      }
    },
    [filteredCommands, selectedIndex, onClose]
  );

  // Scroll automático para item selecionado
  useEffect(() => {
    if (listRef.current) {
      const selectedElement = listRef.current.children[
        selectedIndex
      ] as HTMLElement;
      if (selectedElement) {
        selectedElement.scrollIntoView({
          block: "nearest",
          behavior: "smooth",
        });
      }
    }
  }, [selectedIndex]);

  // Focus automático no input
  useEffect(() => {
    inputRef.current?.focus();
  }, []);

  // Listeners de teclado
  useEffect(() => {
    document.addEventListener("keydown", handleKeyDown);
    return () => document.removeEventListener("keydown", handleKeyDown);
  }, [handleKeyDown]);

  // Reset selected index quando search muda
  useEffect(() => {
    setSelectedIndex(0);
  }, [search]);

  // Click fora fecha modal
  const handleBackdropClick = (e: React.MouseEvent) => {
    if (e.target === e.currentTarget) {
      onClose();
    }
  };

  return (
    <div
      className="fixed inset-0 z-[9999] flex items-start justify-center bg-black/50 backdrop-blur-sm pt-[20vh]"
      onClick={handleBackdropClick}
    >
      <div
        className="w-full max-w-2xl mx-4 bg-white dark:bg-gray-800 rounded-xl shadow-2xl overflow-hidden animate-in fade-in zoom-in-95 duration-200"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Search Input */}
        <div className="flex items-center gap-3 px-4 py-3 border-b border-gray-200 dark:border-gray-700">
          <Search className="w-5 h-5 text-gray-400" />
          <input
            ref={inputRef}
            type="text"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder="Digite para buscar ações, páginas..."
            className="flex-1 bg-transparent border-0 outline-none text-gray-900 dark:text-gray-100 placeholder-gray-400"
          />
          <div className="flex items-center gap-2 text-xs text-gray-500">
            <kbd className="px-2 py-1 bg-gray-100 dark:bg-gray-700 rounded border border-gray-300 dark:border-gray-600">
              ESC
            </kbd>
            <span>para fechar</span>
          </div>
        </div>

        {/* Commands List */}
        <div
          ref={listRef}
          className="max-h-[400px] overflow-y-auto overscroll-contain"
        >
          {filteredCommands.length === 0 ? (
            <div className="px-4 py-12 text-center text-gray-500 dark:text-gray-400">
              <Search className="w-8 h-8 mx-auto mb-2 opacity-50" />
              <p>Nenhum comando encontrado</p>
              <p className="text-sm mt-1">
                Tente buscar por "consulta", "paciente" ou "dashboard"
              </p>
            </div>
          ) : (
            <div className="py-2">
              {filteredCommands.map((command, index) => {
                const Icon = command.icon;
                const isSelected = index === selectedIndex;

                return (
                  <button
                    key={command.id}
                    onClick={() => command.action()}
                    onMouseEnter={() => setSelectedIndex(index)}
                    className={`
                      w-full flex items-center gap-3 px-4 py-3 text-left transition-colors
                      ${
                        isSelected
                          ? "bg-green-50 dark:bg-green-900/20 border-l-2 border-green-600"
                          : "hover:bg-gray-50 dark:hover:bg-gray-700/50"
                      }
                    `}
                  >
                    <Icon
                      className={`w-5 h-5 ${
                        isSelected ? "text-green-600" : "text-gray-400"
                      }`}
                    />
                    <div className="flex-1 min-w-0">
                      <p
                        className={`text-sm font-medium ${
                          isSelected
                            ? "text-green-900 dark:text-green-100"
                            : "text-gray-900 dark:text-gray-100"
                        }`}
                      >
                        {command.label}
                      </p>
                      {command.description && (
                        <p className="text-xs text-gray-500 dark:text-gray-400 truncate">
                          {command.description}
                        </p>
                      )}
                    </div>
                    {isSelected && (
                      <ArrowRight className="w-4 h-4 text-green-600" />
                    )}
                  </button>
                );
              })}
            </div>
          )}
        </div>

        {/* Footer com atalhos */}
        <div className="px-4 py-3 bg-gray-50 dark:bg-gray-900 border-t border-gray-200 dark:border-gray-700 flex items-center justify-between text-xs text-gray-500">
          <div className="flex items-center gap-4">
            <div className="flex items-center gap-1">
              <kbd className="px-1.5 py-0.5 bg-white dark:bg-gray-800 rounded border border-gray-300 dark:border-gray-600">
                ↑
              </kbd>
              <kbd className="px-1.5 py-0.5 bg-white dark:bg-gray-800 rounded border border-gray-300 dark:border-gray-600">
                ↓
              </kbd>
              <span className="ml-1">navegar</span>
            </div>
            <div className="flex items-center gap-1">
              <kbd className="px-1.5 py-0.5 bg-white dark:bg-gray-800 rounded border border-gray-300 dark:border-gray-600">
                Enter
              </kbd>
              <span className="ml-1">selecionar</span>
            </div>
          </div>
          <div className="flex items-center gap-1">
            <Command className="w-3 h-3" />
            <span>+ K para abrir</span>
          </div>
        </div>
      </div>
    </div>
  );
}
