"use client"

import type { IModalProps } from "./Modal.d"
import type { JSX } from "react"

import ReactModal from "react-modal"
import { Theme } from "@radix-ui/themes"
import { X } from "lucide-react"

import styles from "./Modal.module.scss"

if (typeof window !== "undefined") {
	ReactModal.setAppElement("#app-root")
}

const OVERLAY_CLASS = {
	base: styles.overlay,
	afterOpen: styles.overlayAfterOpen,
	beforeClose: styles.overlayBeforeClose,
}

const CONTENT_CLASS = {
	base: styles.content,
	afterOpen: styles.contentAfterOpen,
	beforeClose: styles.contentBeforeClose,
}

export const Modal = ({
	open,
	onOpenChange,
	title,
	description,
	children,
	maxWidth,
}: IModalProps): JSX.Element => (
	<ReactModal
		isOpen={open}
		onRequestClose={() => onOpenChange?.(false)}
		shouldCloseOnOverlayClick
		shouldCloseOnEsc
		closeTimeoutMS={250}
		overlayClassName={OVERLAY_CLASS}
		className={CONTENT_CLASS}
		style={maxWidth ? { content: { maxWidth } } : undefined}
	>
		<Theme accentColor="plum" grayColor="mauve" appearance="inherit">
			{title && <h2 className={styles.title}>{title}</h2>}
			{description && (
				<p className={styles.description}>{description}</p>
			)}
			<button
				type="button"
				className={styles.close}
				onClick={() => onOpenChange?.(false)}
				aria-label="Закрыть"
			>
				<X size={16} />
			</button>
			{children}
		</Theme>
	</ReactModal>
)

Modal.displayName = "Modal"
