import { Dialog, DialogPanel, DialogTitle, Transition, TransitionChild } from "@headlessui/react";
import clsx from "clsx";
import { Fragment, ReactElement, useCallback, useEffect, useState } from "react";

interface Props {
	isOpen: boolean;
	onClose: () => void;
	maxWidth?: string;
	title?: string;
	className?: string;
	titleClassName?: string;
	children?: ReactElement;
}

export default function Modal({ isOpen, maxWidth, title, className, titleClassName, onClose, children }: Props) {

	const [isClosing, setIsClosing] = useState(false);
	const [mounted, setMounted] = useState(false);

	useEffect(() => {
		if (isOpen) {
			setMounted(true);
		}
	}, [isOpen]);

	useEffect(() => {
		if (!isOpen && mounted) {
			const timer = setTimeout(() => {
				setMounted(false);
				setIsClosing(false);
			}, 300);
			return () => clearTimeout(timer);
		}
	}, [isOpen, mounted]);

	const blockMultipleClicksClose = useCallback(() => {
		if (isClosing) return;

		setIsClosing(true);
		onClose();

		const timer = setTimeout(() => {
			setIsClosing(false);
		}, 300);

		return () => clearTimeout(timer);
	}, [isClosing, onClose]);

	if (!mounted && !isOpen) return null;

	return (
		<Transition
			appear
			show={isOpen}
			as={Fragment}
			beforeEnter={() => setIsClosing(false)}
			beforeLeave={() => setIsClosing(true)}
			afterLeave={() => {
				setIsClosing(false);
				setMounted(false);
			}}
		>
			<Dialog as="div" className="relative z-[200]" onClose={() => blockMultipleClicksClose()}>
				<TransitionChild
					as={Fragment}
					enter="ease-out duration-300"
					enterFrom="opacity-0"
					enterTo="opacity-100"
					leave="ease-in duration-200"
					leaveFrom="opacity-100"
					leaveTo="opacity-0">
					<div className="fixed inset-0 bg-black bg-opacity-25" />
				</TransitionChild>

				<div className="fixed inset-0 overflow-y-auto">
					<div className="flex min-h-full items-center justify-center p-4 text-center">
						<TransitionChild
							as={Fragment}
							enter="ease-out duration-300"
							enterFrom="opacity-0 scale-95"
							enterTo="opacity-100 scale-100"
							leave="ease-in duration-200"
							leaveFrom="opacity-100 scale-100"
							leaveTo="opacity-0 scale-95">
							<DialogPanel
								className={clsx(
									"w-full transform overflow-hidden rounded-2xl bg-white p-6 text-left align-middle shadow-xl transition-all",
									!!maxWidth ? maxWidth : 'max-w-6xl',
									className,
								)}>
								{title && (
									<DialogTitle as="h3" className={clsx(titleClassName ? titleClassName : "text-lg font-medium leading-6 text-gray-900")}>
										{title}
									</DialogTitle>
								)}
								{children}
							</DialogPanel>
						</TransitionChild>
					</div>
				</div>
			</Dialog>
		</Transition>
	);
}
