import { createRef, JSX } from 'preact'
import { Button } from '@homeman/components/Button.tsx'
import { useEffect } from 'preact/hooks'

interface Props extends JSX.HTMLAttributes<HTMLDialogElement> {
	headerTitle: string
	show?: boolean
}

export function Dialog(
	{ show, headerTitle, children, className, ...props }: Props,
) {
	const self = createRef<HTMLDialogElement>()

	useEffect(() => {
		if (show) {
			self.current?.showModal()
		} else {
			self.current?.close()
		}
		return () => {
			// cleanup
		}
	}, [show])

	return (
		<dialog
			{...props}
			class={`rounded drop-shadow-lg backdrop:bg-stone-500/90 ${className}`}
			ref={self}
		>
			<header class='p-4 flex w-full items-center border-b-2 border-stone-500/20'>
				<h1 class='text-xl grow mr-2'>{headerTitle}</h1>
				<Button
					onClick={() => self.current?.close()}
					class='text-xl p-4 border-b-2 mr-4'
				>
					✕
				</Button>
			</header>
			{children}
		</dialog>
	)
}
