import { useEffect, useState, useCallback, useRef } from 'react';
import { Modal } from './Modal';
import styles from './text-prompt-modal.module.css';

interface TextPromptModalProps {
  readonly open: boolean;
  readonly title: string;
  readonly initialValue?: string;
  readonly placeholder?: string;
  readonly confirmLabel?: string;
  readonly cancelLabel?: string;
  readonly multiline?: boolean;
  readonly onConfirm: (value: string) => void;
  readonly onCancel: () => void;
}

/**
 * Lightweight replacement for `window.prompt` — a controlled text input inside
 * the shared Modal. Submits on Enter (or Cmd/Ctrl+Enter for multiline) and
 * cancels on Escape (handled by Modal).
 */
export function TextPromptModal({
  open,
  title,
  initialValue = '',
  placeholder,
  confirmLabel = 'OK',
  cancelLabel = 'Cancel',
  multiline = false,
  onConfirm,
  onCancel,
}: TextPromptModalProps) {
  const [value, setValue] = useState(initialValue);
  const inputRef = useRef<HTMLInputElement | HTMLTextAreaElement | null>(null);

  useEffect(() => {
    if (open) {
      setValue(initialValue);
      // Wait for the modal to mount, then focus + select the input so the
      // user can type or replace immediately.
      requestAnimationFrame(() => {
        const el = inputRef.current;
        if (el) {
          el.focus();
          el.select();
        }
      });
    }
  }, [open, initialValue]);

  const handleConfirm = useCallback(() => {
    onConfirm(value);
  }, [onConfirm, value]);

  const handleKeyDown = useCallback(
    (event: React.KeyboardEvent<HTMLInputElement | HTMLTextAreaElement>) => {
      if (event.key === 'Enter' && (!multiline || event.metaKey || event.ctrlKey)) {
        event.preventDefault();
        handleConfirm();
      }
    },
    [handleConfirm, multiline],
  );

  return (
    <Modal
      open={open}
      onClose={onCancel}
      title={title}
      footer={
        <div className={styles.actions}>
          <button type="button" className={styles.button} onClick={onCancel}>
            {cancelLabel}
          </button>
          <button
            type="button"
            className={`${styles.button} ${styles.buttonPrimary}`}
            onClick={handleConfirm}
          >
            {confirmLabel}
          </button>
        </div>
      }
    >
      {multiline ? (
        <textarea
          ref={inputRef as React.RefObject<HTMLTextAreaElement>}
          className={styles.textarea}
          value={value}
          onChange={(e) => setValue(e.target.value)}
          onKeyDown={handleKeyDown}
          placeholder={placeholder}
          rows={4}
        />
      ) : (
        <input
          ref={inputRef as React.RefObject<HTMLInputElement>}
          type="text"
          className={styles.input}
          value={value}
          onChange={(e) => setValue(e.target.value)}
          onKeyDown={handleKeyDown}
          placeholder={placeholder}
        />
      )}
    </Modal>
  );
}
