import { useState } from "react";
import type { ExtensionDialogState } from "../../types/events";
import styles from "./ExtensionDialogModal.module.css";

interface ExtensionDialogModalProps {
	dialog: ExtensionDialogState;
	onSubmit: (response: Record<string, unknown>) => void;
	onDismiss: () => void;
}

export function ExtensionDialogModal({ dialog, onSubmit, onDismiss }: ExtensionDialogModalProps) {
	const [value, setValue] = useState(dialog.prefill ?? "");

	const submitValue = (payload: Record<string, unknown>) => {
		onSubmit(payload);
	};

	return (
		<div className={styles.overlay} role="presentation" onClick={onDismiss}>
			<div className={styles.modal} role="dialog" aria-modal="true" onClick={(e) => e.stopPropagation()}>
				<div className={styles.title}>{dialog.title}</div>
				{dialog.message ? <div className={styles.message}>{dialog.message}</div> : null}

				{dialog.method === "select" && dialog.options ? (
					<div className={styles.options}>
						{dialog.options.map((option) => (
							<button
								key={option}
								type="button"
								className={styles.optionBtn}
								onClick={() => submitValue({ value: option })}
							>
								{option}
							</button>
						))}
						<button type="button" className={styles.optionBtn} onClick={() => submitValue({ cancelled: true })}>
							取消
						</button>
					</div>
				) : null}

				{dialog.method === "confirm" ? (
					<div className={styles.actions}>
						<button type="button" className={styles.btn} onClick={() => submitValue({ cancelled: true })}>
							取消
						</button>
						<button type="button" className={styles.btnPrimary} onClick={() => submitValue({ confirmed: true })}>
							确认
						</button>
					</div>
				) : null}

				{dialog.method === "input" || dialog.method === "editor" ? (
					<>
						<textarea
							className={styles.input}
							rows={dialog.method === "editor" ? 8 : 3}
							value={value}
							onChange={(e) => setValue(e.target.value)}
						/>
						<div className={styles.actions}>
							<button type="button" className={styles.btn} onClick={() => submitValue({ cancelled: true })}>
								取消
							</button>
							<button
								type="button"
								className={styles.btnPrimary}
								onClick={() => submitValue({ value })}
							>
								确定
							</button>
						</div>
					</>
				) : null}
			</div>
		</div>
	);
}
