'use client';

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

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

  const openModal = useCallback(() => {
    if (!ref.current) return;
    if (isNestingModal) {
      ref.current.showModal();
    } else {
      ref.current.show();
    }
    setOpen(true);
  }, [isNestingModal]);

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

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

  useEffect(() => {
    const dialog = ref.current;
    if (!dialog) return;

    const handleClose = () => setOpen(false);
    dialog.addEventListener('close', handleClose);

    return () => {
      dialog.removeEventListener('close', handleClose);
    };
  }, []);

  return { ref, open, 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) => {
  const handleBackdropClick = (e: React.MouseEvent<HTMLDialogElement>) => {
    if (closeOnBackdrop && e.target === ref.current) {
      ref.current?.close();
    }
  };

  return (
    <dialog
      ref={ref}
      className={cn('modal', className?.modal)}
      onClick={handleBackdropClick}
    >
      <div className={cn('modal-box', className?.modalBox)}>{children}</div>
    </dialog>
  );
};

export default Modal;
