'use client';

import { ReactNode, RefObject, useCallback, useRef, useState } from 'react';
import { cn } from '@/lib/helper';

export const useModal = () => {
  const ref = useRef<HTMLDialogElement>(null);
  const [open, setOpen] = useState(false);

  const openModal = useCallback(() => {
    setOpen(true);

    ref.current?.showModal();
  }, []);

  const closeModal = useCallback(() => {
    setOpen(false);
    ref.current?.close();
  }, []);

  const toggle = useCallback(() => {
    if (open) {
      closeModal();
    } else {
      openModal();
    }
  }, [open, closeModal, openModal]);

  if (ref.current) {
    ref.current.addEventListener('close', () => {
      closeModal();
    });
  }

  return { ref, open, setOpen, openModal, closeModal, toggle } as const;
};

interface ModalProps {
  ref: RefObject<HTMLDialogElement | null>;
  children?: ReactNode;
  closeOnBackdrop?: boolean;
  className?: {
    modal?: string;
    modalBox?: string;
  };
}

const Modal = ({ ref, children, closeOnBackdrop, className }: ModalProps) => {
  return (
    <dialog ref={ref} className={cn('modal', className?.modal)}>
      <div className={cn('modal-box', className?.modalBox)}>{children}</div>

      {closeOnBackdrop && (
        <form method='dialog' className='modal-backdrop'>
          <button>close</button>
        </form>
      )}
    </dialog>
  );
};

export default Modal;
