import React, { useState, useMemo, useRef, useEffect, useCallback } from 'react';
import { Modal, Input, Typography, Tag, Empty, theme } from 'antd';
import {
  SearchOutlined,
  DashboardOutlined,
  BookOutlined,
  FileTextOutlined,
  BankOutlined,
  TeamOutlined,
  ShopOutlined,
  PercentageOutlined,
  ExportOutlined,
  SettingOutlined,
  PlusOutlined,
  SyncOutlined,
  HistoryOutlined,
} from '@ant-design/icons';
import {
  shortcuts,
  navigationRoutes,
  formatShortcut,
} from '@/lib/keyboardShortcuts';
import { useRecentCommands } from '@/stores/hotkeyStore';

const { Text } = Typography;
const { useToken } = theme;

interface CommandPaletteProps {
  open: boolean;
  onClose: () => void;
  onExecute: (commandId: string, route?: string) => void;
  currentPath: string;
}

interface CommandItem {
  id: string;
  label: string;
  description?: string;
  icon: React.ReactNode;
  shortcut?: string;
  category: 'recent' | 'navigation' | 'action';
  route?: string;
}

// Icon mapping for navigation items
const navigationIcons: Record<string, React.ReactNode> = {
  goToDashboard: <DashboardOutlined />,
  goToKassekladde: <BookOutlined />,
  goToKontooversigt: <BookOutlined />,
  goToFakturaer: <FileTextOutlined />,
  goToKreditnotaer: <FileTextOutlined />,
  goToBankafstemning: <BankOutlined />,
  goToKunder: <TeamOutlined />,
  goToProdukter: <ShopOutlined />,
  goToMomsindberetning: <PercentageOutlined />,
  goToIndstillinger: <SettingOutlined />,
};

// Action commands (not navigation)
const actionCommands: CommandItem[] = [
  {
    id: 'newDraft',
    label: 'Ny kassekladde',
    description: 'Opret en ny kassekladde',
    icon: <PlusOutlined />,
    shortcut: shortcuts.newDraft?.keys,
    category: 'action',
    route: '/kassekladde?action=new',
  },
  {
    id: 'newInvoice',
    label: 'Ny faktura',
    description: 'Opret en ny faktura',
    icon: <PlusOutlined />,
    shortcut: shortcuts.newInvoice?.keys,
    category: 'action',
    route: '/fakturaer?action=new',
  },
  {
    id: 'newCustomer',
    label: 'Ny kunde',
    description: 'Opret en ny kunde',
    icon: <PlusOutlined />,
    shortcut: shortcuts.newCustomer?.keys,
    category: 'action',
    route: '/kunder?action=new',
  },
  {
    id: 'newProduct',
    label: 'Nyt produkt',
    description: 'Opret et nyt produkt',
    icon: <PlusOutlined />,
    shortcut: shortcuts.newProduct?.keys,
    category: 'action',
    route: '/produkter?action=new',
  },
  {
    id: 'syncBank',
    label: 'Synkroniser bank',
    description: 'Hent nye transaktioner fra bank',
    icon: <SyncOutlined />,
    shortcut: shortcuts.syncBank?.keys,
    category: 'action',
    route: '/bankafstemning?action=sync',
  },
  {
    id: 'exportSaft',
    label: 'Eksporter SAF-T',
    description: 'Eksporter regnskabsdata til SAF-T format',
    icon: <ExportOutlined />,
    category: 'action',
    route: '/eksport',
  },
];

/**
 * CommandPalette - Cmd+K quick navigation and actions
 */
export function CommandPalette({
  open,
  onClose,
  onExecute,
  currentPath,
}: CommandPaletteProps) {
  const [searchValue, setSearchValue] = useState('');
  const [selectedIndex, setSelectedIndex] = useState(0);
  const inputRef = useRef<HTMLInputElement>(null);
  const listRef = useRef<HTMLDivElement>(null);
  const { token } = useToken();
  const recentCommands = useRecentCommands();

  // Build navigation commands from shortcuts
  const navigationCommands: CommandItem[] = useMemo(() => {
    return Object.entries(navigationRoutes).map(([shortcutId, route]) => {
      const shortcut = shortcuts[shortcutId];
      return {
        id: shortcutId,
        label: shortcut?.label || shortcutId,
        icon: navigationIcons[shortcutId] || <DashboardOutlined />,
        shortcut: shortcut?.keys,
        category: 'navigation' as const,
        route,
      };
    });
  }, []);

  // Build recent commands
  const recentItems: CommandItem[] = useMemo(() => {
    return recentCommands.map((cmd) => {
      // Find if it's a navigation or action command
      const navCmd = navigationCommands.find((n) => n.id === cmd.id);
      const actionCmd = actionCommands.find((a) => a.id === cmd.id);
      const source = navCmd || actionCmd;

      return {
        id: cmd.id,
        label: cmd.label,
        icon: source?.icon || <HistoryOutlined />,
        shortcut: source?.shortcut,
        category: 'recent' as const,
        route: source?.route,
      };
    });
  }, [recentCommands, navigationCommands]);

  // Filter commands based on search
  const filteredCommands = useMemo(() => {
    const query = searchValue.toLowerCase().trim();

    // All available commands
    const allCommands = [
      ...recentItems,
      ...navigationCommands,
      ...actionCommands,
    ];

    if (!query) {
      // No search - show recent first, then navigation, then actions
      // But deduplicate (recent items appear first, not duplicated)
      const recentIds = new Set(recentItems.map((r) => r.id));
      const dedupedNav = navigationCommands.filter((n) => !recentIds.has(n.id));
      const dedupedActions = actionCommands.filter((a) => !recentIds.has(a.id));

      return [...recentItems, ...dedupedNav, ...dedupedActions];
    }

    // Filter by search query (fuzzy match on label)
    return allCommands.filter((cmd) => {
      const labelMatch = cmd.label.toLowerCase().includes(query);
      const descMatch = cmd.description?.toLowerCase().includes(query);
      return labelMatch || descMatch;
    });
  }, [searchValue, recentItems, navigationCommands]);

  // Reset selection when search changes or modal opens
  useEffect(() => {
    setSelectedIndex(0);
  }, [searchValue, open]);

  // Focus input when modal opens
  useEffect(() => {
    if (open) {
      setSearchValue('');
      setTimeout(() => {
        inputRef.current?.focus();
      }, 50);
    }
  }, [open]);

  // Scroll selected item into view
  useEffect(() => {
    if (listRef.current) {
      const selectedElement = listRef.current.querySelector(
        `[data-index="${selectedIndex}"]`
      );
      if (selectedElement) {
        selectedElement.scrollIntoView({ block: 'nearest' });
      }
    }
  }, [selectedIndex]);

  // Handle keyboard navigation
  const handleKeyDown = useCallback(
    (e: React.KeyboardEvent) => {
      switch (e.key) {
        case 'ArrowDown':
          e.preventDefault();
          setSelectedIndex((i) =>
            i < filteredCommands.length - 1 ? i + 1 : 0
          );
          break;
        case 'ArrowUp':
          e.preventDefault();
          setSelectedIndex((i) =>
            i > 0 ? i - 1 : filteredCommands.length - 1
          );
          break;
        case 'Enter':
          e.preventDefault();
          const selected = filteredCommands[selectedIndex];
          if (selected) {
            handleExecute(selected);
          }
          break;
        case 'Escape':
          e.preventDefault();
          onClose();
          break;
      }
    },
    [filteredCommands, selectedIndex, onClose]
  );

  // Execute command
  const handleExecute = useCallback(
    (command: CommandItem) => {
      onExecute(command.id, command.route);
      onClose();
    },
    [onExecute, onClose]
  );

  // Category labels
  const getCategoryLabel = (category: string): string => {
    switch (category) {
      case 'recent':
        return 'Seneste';
      case 'navigation':
        return 'Navigation';
      case 'action':
        return 'Handlinger';
      default:
        return category;
    }
  };

  // Group commands by category for display
  const groupedCommands = useMemo(() => {
    const groups: Record<string, CommandItem[]> = {};
    filteredCommands.forEach((cmd) => {
      if (!groups[cmd.category]) {
        groups[cmd.category] = [];
      }
      groups[cmd.category].push(cmd);
    });
    return groups;
  }, [filteredCommands]);

  return (
    <Modal
      open={open}
      onCancel={onClose}
      footer={null}
      closable={false}
      centered
      width={560}
      styles={{
        body: { padding: 0 },
        content: { borderRadius: 12, overflow: 'hidden' },
      }}
      maskClosable
    >
      <div onKeyDown={handleKeyDown}>
        {/* Search input */}
        <div
          style={{
            padding: '12px 16px',
            borderBottom: `1px solid ${token.colorBorderSecondary}`,
          }}
        >
          <Input
            ref={inputRef as React.RefObject<any>}
            placeholder="Søg efter sider eller handlinger..."
            prefix={<SearchOutlined style={{ color: token.colorTextSecondary }} />}
            value={searchValue}
            onChange={(e) => setSearchValue(e.target.value)}
            variant="borderless"
            size="large"
            style={{ fontSize: 16 }}
            autoComplete="off"
          />
        </div>

        {/* Results list */}
        <div
          ref={listRef}
          style={{
            maxHeight: 400,
            overflowY: 'auto',
            padding: '8px 0',
          }}
        >
          {filteredCommands.length === 0 ? (
            <Empty
              image={Empty.PRESENTED_IMAGE_SIMPLE}
              description="Ingen resultater"
              style={{ padding: '32px 0' }}
            />
          ) : (
            Object.entries(groupedCommands).map(([category, commands]) => (
              <div key={category}>
                {/* Category header */}
                <div
                  style={{
                    padding: '8px 16px 4px',
                    fontSize: 12,
                    fontWeight: 500,
                    color: token.colorTextSecondary,
                    textTransform: 'uppercase',
                    letterSpacing: '0.5px',
                  }}
                >
                  {getCategoryLabel(category)}
                </div>

                {/* Command items */}
                {commands.map((command) => {
                  const globalIndex = filteredCommands.indexOf(command);
                  const isSelected = globalIndex === selectedIndex;
                  const isCurrent = command.route === currentPath;

                  return (
                    <div
                      key={`${command.category}-${command.id}`}
                      data-index={globalIndex}
                      onClick={() => handleExecute(command)}
                      style={{
                        display: 'flex',
                        alignItems: 'center',
                        padding: '10px 16px',
                        cursor: 'pointer',
                        backgroundColor: isSelected
                          ? token.colorPrimaryBg
                          : 'transparent',
                        borderLeft: isSelected
                          ? `3px solid ${token.colorPrimary}`
                          : '3px solid transparent',
                        transition: 'background-color 0.15s',
                      }}
                      onMouseEnter={() => setSelectedIndex(globalIndex)}
                    >
                      {/* Icon */}
                      <span
                        style={{
                          marginRight: 12,
                          fontSize: 16,
                          color: isSelected
                            ? token.colorPrimary
                            : token.colorTextSecondary,
                        }}
                      >
                        {command.icon}
                      </span>

                      {/* Label and description */}
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div
                          style={{
                            display: 'flex',
                            alignItems: 'center',
                            gap: 8,
                          }}
                        >
                          <Text
                            strong={isSelected}
                            style={{
                              color: isSelected
                                ? token.colorText
                                : token.colorTextSecondary,
                            }}
                          >
                            {command.label}
                          </Text>
                          {isCurrent && (
                            <Tag
                              color="blue"
                              style={{ margin: 0, fontSize: 10 }}
                            >
                              Aktuel
                            </Tag>
                          )}
                        </div>
                        {command.description && (
                          <Text
                            type="secondary"
                            style={{ fontSize: 12 }}
                          >
                            {command.description}
                          </Text>
                        )}
                      </div>

                      {/* Shortcut badge */}
                      {command.shortcut && (
                        <div
                          style={{
                            display: 'flex',
                            gap: 4,
                          }}
                        >
                          {formatShortcut(command.shortcut)
                            .split(' ')
                            .map((key, i) => (
                              <Tag
                                key={i}
                                style={{
                                  margin: 0,
                                  padding: '0 6px',
                                  fontSize: 11,
                                  fontFamily: 'monospace',
                                  backgroundColor: token.colorFillTertiary,
                                  border: `1px solid ${token.colorBorderSecondary}`,
                                  borderRadius: 4,
                                }}
                              >
                                {key}
                              </Tag>
                            ))}
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            ))
          )}
        </div>

        {/* Footer hint */}
        <div
          style={{
            padding: '8px 16px',
            borderTop: `1px solid ${token.colorBorderSecondary}`,
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
            fontSize: 12,
            color: token.colorTextSecondary,
          }}
        >
          <span>
            <Tag style={{ margin: 0, marginRight: 4 }}>↑↓</Tag>
            Navigér
            <Tag style={{ margin: '0 4px' }}>↵</Tag>
            Vælg
            <Tag style={{ margin: '0 4px' }}>Esc</Tag>
            Luk
          </span>
        </div>
      </div>
    </Modal>
  );
}

export default CommandPalette;
