import { useSuspendPlayback } from '@/hooks/use-suspend-playback';
import { useEffect } from 'react';
import { createPortal } from 'react-dom';
import { KeyHint } from '@/components/key-hint';

export interface KeybindingEntry {
  keys: string[];
  description: string;
}

export interface KeybindingGroup {
  label: string;
  bindings: KeybindingEntry[];
}

interface KeybindingsOverlayProps {
  open: boolean;
  onClose: () => void;
  groups: KeybindingGroup[];
  title?: string;
}

export function KeybindingsOverlay({
  open,
  onClose,
  groups,
  title = 'Keyboard Shortcuts',
}: KeybindingsOverlayProps) {
  useSuspendPlayback(open, 'keybindings');

  useEffect(() => {
    if (!open) return;
    const handler = (e: KeyboardEvent) => {
      if (e.key === 'Escape' || e.key === '?') {
        e.preventDefault();
        e.stopPropagation();
        onClose();
      }
    };
    window.addEventListener('keydown', handler, { capture: true });
    return () =>
      window.removeEventListener('keydown', handler, { capture: true });
  }, [open, onClose]);

  if (!open) return null;

  return createPortal(
    <div className="fixed inset-0 z-[100]">
      {/* Backdrop */}
      <div
        className="absolute inset-0 bg-black/60 backdrop-blur-sm"
        onClick={onClose}
      />
      {/* Panel */}
      <div className="absolute left-1/2 top-1/2 w-full max-w-sm -translate-x-1/2 -translate-y-1/2 rounded-2xl border border-white/10 bg-white/5 p-6 shadow-2xl backdrop-blur-xl">
        <div className="mb-5 flex items-center justify-between">
          <h2 className="text-sm font-semibold text-white/70">{title}</h2>
          <KeyHint
            keys={['Esc', '?']}
            separator="or"
            onClick={onClose}
            title="Close (or press Esc / ?)"
            className="text-xs text-white/30"
          >
            to close
          </KeyHint>
        </div>
        <div className="flex flex-col gap-5">
          {groups.map((group) => (
            <section key={group.label}>
              <h3 className="mb-2 text-[10px] font-medium uppercase tracking-widest text-white/30">
                {group.label}
              </h3>
              <ul className="flex flex-col gap-1">
                {group.bindings.map((binding) => (
                  <li
                    key={binding.description}
                    className="flex items-center justify-between border-b border-white/5 pb-1 last:border-0 last:pb-0"
                  >
                    <span className="text-sm text-white/70">
                      {binding.description}
                    </span>
                    <KeyHint
                      keys={binding.keys}
                      className="flex items-center gap-1 text-white/60"
                    />
                  </li>
                ))}
              </ul>
            </section>
          ))}
        </div>
      </div>
    </div>,
    document.body,
  );
}
