import * as Dialog from '@radix-ui/react-dialog';
import Icon from '../../utils/Icon';
import React from 'react';

interface ModalProps {
	title?: string;
	subtitle?: string;
	customHeader?: React.ReactNode;
	content: React.ReactNode;
	footer?: React.ReactNode;
	triggerClassName?: string;
	children?: React.ReactNode;
	isOpen: boolean;
	onClose: () => void;
	size?: 'default' | 'full';
	onPointerDownOutside?: React.ComponentProps<typeof Dialog.Content>['onPointerDownOutside'];
	onInteractOutside?: React.ComponentProps<typeof Dialog.Content>['onInteractOutside'];
}

// fallow-ignore-next-line complexity
const Modal: React.FC<ModalProps> = ({
	title,
	subtitle = '',
	customHeader = null,
	content,
	footer,
	triggerClassName,
	children,
	isOpen,
	onClose,
	size = 'default',
	onPointerDownOutside,
	onInteractOutside
}) => {
	const isDismissingPopperRef = React.useRef( false );

	React.useEffect( () => {
		if ( ! isOpen ) {
			return;
		}
		const handlePointerDown = () => {
			const hasOpenPopper = null !== document.getElementById( 'modal-root' )?.querySelector( '[data-radix-popper-content-wrapper]' );
			if ( hasOpenPopper ) {
				isDismissingPopperRef.current = true;
			} else {
				isDismissingPopperRef.current = false;
			}
		};
		document.addEventListener( 'pointerdown', handlePointerDown, true );
		return () => {
			document.removeEventListener( 'pointerdown', handlePointerDown, true );
		};
	}, [ isOpen ]);

	const contentSizeClasses =
		'full' === size ?
			'@md:w-[calc(100%-40px)] @md:max-w-(--breakpoint-2xl) @xl:w-[calc(100%-64px)]' :
			'@md:w-full @md:max-w-[720px]';

	return (
		<Dialog.Root
			open={isOpen}
			onOpenChange={( open ) => {
				if ( ! open ) {
					onClose?.();
				}
			}}
		>
			{triggerClassName && (
				<Dialog.Trigger className={triggerClassName}>
					{children}
				</Dialog.Trigger>
			)}
			<Dialog.Portal container={document.getElementById( 'modal-root' )}>
				<Dialog.Overlay className="bg-black/50 fixed inset-0 z-9999" />
				<Dialog.Content
					onPointerDownOutside={( e ) => {
						if ( isDismissingPopperRef.current ) {
							e.preventDefault();
							isDismissingPopperRef.current = false;
						}
						onPointerDownOutside?.( e );
					}}
					onInteractOutside={( e ) => {
						if ( isDismissingPopperRef.current ) {
							e.preventDefault();
							isDismissingPopperRef.current = false;
						}
						onInteractOutside?.( e );
					}}
					className={`fixed top-[calc(var(--wp-admin--admin-bar--height,0px)+12px)] left-1/2 -translate-x-1/2 w-[calc(100%-20px)] max-h-[90vh] m-0 px-4 py-3 rounded-md z-9999 bg-gray-100 shadow-md focus:outline-hidden data-[state=open]:animate-contentShow flex flex-col overflow-x-visible ${contentSizeClasses}`}
				>
					<div className="flex flex-row justify-between items-center shrink-0">
						{customHeader ? (
							<>
								<Dialog.Title className="sr-only">{title}</Dialog.Title>
								<div className="flex-1">{customHeader}</div>
								<Dialog.Close asChild>
									<button
										aria-label="Close"
										onClick={onClose}
										className="bg-gray-200 rounded-full p-2 w-8 h-8 cursor-pointer hover:bg-gray-300 transition-colors duration-150 ml-4"
									>
										<Icon
											name={'times'}
											size={18}
											color={'gray'}
										/>
									</button>
								</Dialog.Close>
							</>
						) : (
							<>
								<div>
									<Dialog.Title className="text-lg font-semibold text-text-black">
										{title}
									</Dialog.Title>
									{subtitle && (
										<p className="text-sm text-text-gray">
											{subtitle}
										</p>
									)}
								</div>
								<Dialog.Close asChild>
									<button
										aria-label="Close"
										onClick={onClose}
										className="bg-gray-200 rounded-full p-2 w-8 h-8 cursor-pointer hover:bg-gray-300 transition-colors duration-150"
									>
										<Icon
											name={'times'}
											size={18}
											color={'gray'}
										/>
									</button>
								</Dialog.Close>
							</>
						)}
					</div>
					<Dialog.Description className="text-base text-text-black mb-6 mt-4 flex-1 overflow-y-auto overflow-x-visible min-h-0">
						{content}
					</Dialog.Description>
					{footer && (
						<div className="flex flex-row justify-end gap-2 shrink-0 bottom-0 bg-gray-100 pt-4 border-t border-gray-200 mx-4 px-4">
							{footer}
						</div>
					)}
				</Dialog.Content>
			</Dialog.Portal>
		</Dialog.Root>
	);
};

export default Modal;
