import { KeyboardEvent, ReactNode, useRef, useState } from "react";
import { useTranslation } from "react-i18next";

import { ArrowDownIcon, CloseIcon } from "./icons";

type Props = {
	onBack: () => void;
	onClose: () => void;
	backTitleKey: string;
	content: ReactNode;
};

export function DialogContainer({
	onBack,
	onClose,
	backTitleKey,
	content,
}: Props) {
	const { t } = useTranslation();
	const [isOpen, setIsOpen] = useState(true);
	const dialogRef = useRef<HTMLDialogElement>(null);

	function handleKeyDown(e: KeyboardEvent<HTMLDialogElement>) {
		if (e.key === "Escape") {
			close();
		}
	}

	function close() {
		setIsOpen(false);
		onClose();
	}

	return (
		<dialog
			open={isOpen}
			className="fixed inset-0 z-10 overflow-y-auto"
			onKeyDown={handleKeyDown}
			autoFocus
			ref={dialogRef}
		>
			<div className="bg-white rounded-lg shadow-lg p-4">
				<div className="flex justify-between items-center">
					<div className="flex items-center">
						<button
							type="button"
							className="flex items-center gap-2"
							onClick={onBack}
							title={backTitleKey}
						>
							<ArrowDownIcon
								angle={90}
								color="var(--black-800)"
							/>
							{t(backTitleKey)}
						</button>
						<button
							type="button"
							className="flex items-center gap-2"
							onClick={close}
							title={t("Close")}
						>
							<CloseIcon color="#FF3B30" />
						</button>
					</div>

					<div className="">
						<div className="">{content}</div>
					</div>
				</div>
			</div>
		</dialog>
	);
}
