import type { ReactNode } from 'react';

import { Button } from '../button/Button';
import type { ModalRootProps } from './Modal';
import { ModalBody, ModalFooter, ModalHeader, ModalRoot } from './Modal';

interface AlertModalProps {
  isOpen?: ModalRootProps['isOpen'];
  onOpenChange?: ModalRootProps['onOpenChange'];
  title?: string;
  content?: ReactNode;
  confirmText?: string;
  onConfirm?: () => void;
}

export const AlertModal = (props: AlertModalProps) => {
  const { isOpen, onOpenChange, title, ...contentProps } = props;

  return (
    <ModalRoot isOpen={isOpen} onOpenChange={onOpenChange} className="w-75" aria-label={title ?? '알림'}>
      {({ close }) => <AlertModalContent close={close} title={title} {...contentProps} />}
    </ModalRoot>
  );
};

function AlertModalContent({
  close,
  title,
  content,
  confirmText = '확인',
  onConfirm,
}: {
  close: () => void;
  title?: string;
  content?: ReactNode;
  confirmText?: string;
  onConfirm?: () => void;
}) {
  const handleConfirm = () => {
    onConfirm?.();
    close();
  };

  return (
    <>
      {title && <ModalHeader>{title}</ModalHeader>}
      <ModalBody className="px-7.5 py-8">
        <p className="text-sm text-dabeeo-black-34 font-medium text-center whitespace-pre-wrap">{content}</p>
      </ModalBody>
      <ModalFooter>
        <Button color="gray" size="large" autoFocus onClick={handleConfirm}>
          {confirmText}
        </Button>
      </ModalFooter>
    </>
  );
}
