import * as React from 'react';
import { cn } from '../../lib/utils';
import { Button } from './button';

export interface FormDialogProps {
  ariaLabel?: string;
  bodyClassName?: string;
  children: React.ReactNode;
  className?: string;
  closeLabel?: string;
  eyebrow?: string;
  footer: React.ReactNode;
  formClassName?: string;
  open: boolean;
  title: string;
  onClose: () => void;
  onSubmit: React.FormEventHandler<HTMLFormElement>;
}

export function FormDialog(props: FormDialogProps) {
  const { onClose, open } = props;

  React.useEffect(() => {
    if (!open) return undefined;
    function onKeyDown(event: KeyboardEvent) {
      if (event.key === 'Escape') onClose();
    }
    window.addEventListener('keydown', onKeyDown);
    return () => window.removeEventListener('keydown', onKeyDown);
  }, [onClose, open]);

  if (!open) return null;

  const closeLabel = props.closeLabel ?? '关闭';

  return (
    <div className="formDialogBackdrop" role="presentation">
      <div className={cn('formDialog', props.className)} role="dialog" aria-modal="true" aria-label={props.ariaLabel ?? props.title}>
        <header className="formDialogHeader">
          <div>
            {props.eyebrow && <span>{props.eyebrow}</span>}
            <strong>{props.title}</strong>
          </div>
          <Button type="button" variant="ghost" size="sm" onClick={props.onClose}>{closeLabel}</Button>
        </header>
        <form className={cn('formDialogForm', props.formClassName)} onSubmit={props.onSubmit}>
          <div className={cn('formDialogBody', props.bodyClassName)}>{props.children}</div>
          <div className="formDialogActions">{props.footer}</div>
        </form>
      </div>
    </div>
  );
}
