'use client';

/**
 * Keyboard shortcuts help sheet — triggered by pressing `?`.
 * Shows all registered shortcuts from useKeyboardShortcut.
 */

import { useState, useEffect } from 'react';
import {
  Sheet,
  SheetContent,
  SheetHeader,
  SheetTitle,
  SheetDescription,
} from '@/components/ui/sheet';
import { getRegisteredShortcuts, type ShortcutScope } from '@/hooks/useKeyboardShortcut';
import { registerGlobalKeyboardListener, unregisterGlobalKeyboardListener } from '@/hooks/useKeyboardShortcut';
import {
  Keyboard,
  Globe,
  FileText,
  Puzzle,
} from 'lucide-react';

const SCOPE_LABELS: Record<ShortcutScope, { label: string; Icon: React.ComponentType<{ className?: string }> }> = {
  global: { label: 'Global', Icon: Globe },
  page: { label: 'Page', Icon: FileText },
  component: { label: 'Component', Icon: Puzzle },
};

export function KeyboardShortcutsSheet() {
  const [open, setOpen] = useState(false);

  useEffect(() => {
    registerGlobalKeyboardListener();
    const handleKey = (e: KeyboardEvent) => {
      // Open on `?` when not in an input
      const target = e.target as HTMLElement;
      const isEditing =
        target.tagName === 'INPUT' ||
        target.tagName === 'TEXTAREA' ||
        target.isContentEditable;
      if (e.key === '?' && !isEditing) {
        setOpen((v) => !v);
      }
    };
    window.addEventListener('keydown', handleKey);
    return () => {
      window.removeEventListener('keydown', handleKey);
      unregisterGlobalKeyboardListener();
    };
  }, []);

  const shortcuts = getRegisteredShortcuts();
  const byScope = shortcuts.reduce<Record<ShortcutScope, typeof shortcuts>>((acc, s) => {
    (acc[s.scope] ??= []).push(s);
    return acc;
  }, {} as Record<ShortcutScope, typeof shortcuts>);

  const scopes: ShortcutScope[] = ['global', 'page', 'component'];

  return (
    <Sheet open={open} onOpenChange={setOpen}>
      <SheetContent side="right" className="w-80 overflow-y-auto">
        <SheetHeader className="mb-4">
          <SheetTitle className="flex items-center gap-2">
            <Keyboard className="h-5 w-5" />
            Keyboard Shortcuts
          </SheetTitle>
          <SheetDescription>
            Press{' '}
            <kbd className="inline-flex items-center rounded border bg-muted px-1.5 py-0.5 font-mono text-xs">
              ?
            </kbd>{' '}
            to toggle this panel.
          </SheetDescription>
        </SheetHeader>

        <div className="space-y-6">
          {scopes.map((scope) => {
            const items = byScope[scope];
            if (!items?.length) return null;
            const { label, Icon } = SCOPE_LABELS[scope];
            return (
              <section key={scope}>
                <h3 className="mb-2 flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wider text-muted-foreground">
                  <Icon className="h-3.5 w-3.5" />
                  {label}
                </h3>
                <div className="space-y-0.5">
                  {items.map((s, i) => (
                    <div
                      key={`${s.key}-${s.ctrl ?? ''}-${s.meta ?? ''}-${s.shift ?? ''}-${i}`}
                      className="flex items-center justify-between rounded px-2 py-1.5 hover:bg-muted/60"
                    >
                      <span className="text-sm text-foreground">
                        {s.description ?? s.key}
                      </span>
                      <kbd className="flex items-center gap-0.5 font-mono text-xs">
                        {s.meta && (
                          <span className="rounded border bg-muted px-1 py-0.5 text-[10px]">
                            ⌘
                          </span>
                        )}
                        {s.ctrl && (
                          <span className="rounded border bg-muted px-1 py-0.5 text-[10px]">
                            Ctrl
                          </span>
                        )}
                        {s.alt && (
                          <span className="rounded border bg-muted px-1 py-0.5 text-[10px]">
                            ⌥
                          </span>
                        )}
                        {s.shift && (
                          <span className="rounded border bg-muted px-1 py-0.5 text-[10px]">
                            ⇧
                          </span>
                        )}
                        <span className="rounded border bg-muted px-1 py-0.5 text-[10px]">
                          {s.key.toUpperCase()}
                        </span>
                      </kbd>
                    </div>
                  ))}
                </div>
              </section>
            );
          })}

          {shortcuts.length === 0 && (
            <p className="text-sm text-muted-foreground text-center py-4">
              No shortcuts registered yet.
            </p>
          )}
        </div>

        <div className="mt-6 rounded border border-dashed p-3">
          <p className="text-xs text-muted-foreground text-center">
            Cmd+K opens the command palette
          </p>
        </div>
      </SheetContent>
    </Sheet>
  );
}
