'use client';

import { Modal } from './Modal';
import { cn } from '@/lib/utils';

interface KeyboardShortcut {
  keys: string[];
  description: string;
  category?: string;
}

interface KeyboardShortcutsModalProps {
  isOpen: boolean;
  onClose: () => void;
  shortcuts: KeyboardShortcut[];
  title?: string;
}

function KeyBadge({ keyText }: { keyText: string }) {
  return (
    <kbd className="inline-flex items-center px-1.5 py-0.5 text-xs font-mono font-medium text-[var(--foreground)] bg-[var(--card)] border border-[var(--border)] rounded shadow-sm">
      {keyText}
    </kbd>
  );
}

function ShortcutRow({ shortcut }: { shortcut: KeyboardShortcut }) {
  return (
    <div className="flex items-center justify-between py-1 px-2 rounded hover:bg-[var(--card-hover)] transition-colors">
      <div className="flex items-center gap-1">
        {shortcut.keys.map((key, index) => (
          <div key={index} className="flex items-center gap-0.5">
            <KeyBadge keyText={key} />
            {index < shortcut.keys.length - 1 && (
              <span className="text-[var(--muted-foreground)] text-xs">+</span>
            )}
          </div>
        ))}
      </div>
      <span className="text-xs text-[var(--foreground)] font-mono">
        {shortcut.description}
      </span>
    </div>
  );
}

export function KeyboardShortcutsModal({ 
  isOpen, 
  onClose, 
  shortcuts, 
  title = "Raccourcis clavier" 
}: KeyboardShortcutsModalProps) {
  // Grouper les raccourcis par catégorie
  const groupedShortcuts = shortcuts.reduce((acc, shortcut) => {
    const category = shortcut.category || 'Général';
    if (!acc[category]) {
      acc[category] = [];
    }
    acc[category].push(shortcut);
    return acc;
  }, {} as Record<string, KeyboardShortcut[]>);

  return (
    <Modal isOpen={isOpen} onClose={onClose} title={title} size="md">
      <div className="space-y-4">
        {Object.entries(groupedShortcuts).map(([category, categoryShortcuts]) => (
          <div key={category}>
            <h3 className="text-xs font-mono font-semibold text-[var(--primary)] uppercase tracking-wider mb-2">
              {category}
            </h3>
            <div className="space-y-0.5">
              {categoryShortcuts.map((shortcut, index) => (
                <ShortcutRow key={index} shortcut={shortcut} />
              ))}
            </div>
          </div>
        ))}
        
        {shortcuts.length === 0 && (
          <div className="text-center py-6">
            <p className="text-xs text-[var(--muted-foreground)] font-mono">
              Aucun raccourci disponible sur cette page
            </p>
          </div>
        )}
      </div>
      
      {/* Footer avec info */}
      <div className="mt-4 pt-3 border-t border-[var(--border)]/50">
        <p className="text-xs text-[var(--muted-foreground)] font-mono text-center">
          <KeyBadge keyText="Esc" /> pour fermer
        </p>
      </div>
    </Modal>
  );
}
