import { useEffect, useRef, type ReactNode } from 'react';

import { Button } from '@/components/ui/Button';
import { SectionHeader } from '@/components/ui/SectionHeader';
import { type Accent } from '@/lib/cn';

interface ModalProps {
  open: boolean;
  title: string;
  accent?: Accent;
  onClose: () => void;
  children: ReactNode;
  /** Optional name to give the dialog role for screen readers / Playwright. */
  testid?: string;
}

/**
 * Centered modal with a backdrop. Closes on Escape and on backdrop click.
 * The accessible name comes from the SectionHeader's `highlight`, so the dialog
 * can be located via `getByRole('dialog', { name: ... })`.
 */
export function Modal({ open, title, accent = 'cyan', onClose, children, testid }: ModalProps) {
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!open) return;
    function onKey(e: KeyboardEvent) {
      if (e.key === 'Escape') onClose();
    }
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [open, onClose]);

  if (!open) return null;

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4"
      onMouseDown={(e) => {
        if (e.target === e.currentTarget) onClose();
      }}
      role="presentation"
    >
      <div
        ref={ref}
        role="dialog"
        aria-modal="true"
        aria-label={title}
        data-testid={testid}
        className="w-full max-w-2xl rounded-lg border border-border bg-bg-base p-6 shadow-2xl"
      >
        <div className="flex items-start justify-between gap-4">
          <SectionHeader prefix="Edit" highlight={title} accent={accent} className="mt-0 mb-4" />
          <Button variant="ghost" onClick={onClose} aria-label="Close dialog">
            ✕
          </Button>
        </div>
        {children}
      </div>
    </div>
  );
}
