import { FC, PropsWithChildren, useEffect, useRef } from 'react';

interface DialogProps {
  visible: boolean;
  closeDialog: () => void;
}

const Dialog: FC<PropsWithChildren<DialogProps>> = ({
  visible,
  closeDialog,
  children,
}) => {
  const dialogRef = useRef<HTMLDialogElement>(null);

  useEffect(() => {
    if (visible) {
      dialogRef.current?.showModal();
    } else {
      dialogRef.current?.close();
    }
  }, [visible]);

  const handleButtonClick = (e: React.MouseEvent<HTMLButtonElement>) => {
    e.preventDefault();
    closeDialog();
  };

  return (
    <dialog ref={dialogRef}>
      <div className="p-4 flex flex-col max-w-[90vw] md:max-w-[50vw] bg-white shadow">
        <div className="flex w-full">
          <button className="ml-auto" onClick={handleButtonClick}>
            <svg
              xmlns="http://www.w3.org/2000/svg"
              fill="none"
              viewBox="0 0 24 24"
              strokeWidth={1.5}
              stroke="currentColor"
              className="w-6 h-6">
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M6 18 18 6M6 6l12 12"
              />
            </svg>
          </button>
        </div>
        {children}
      </div>
    </dialog>
  );
};

export default Dialog;
