'use client';

import { FC, ReactNode, useEffect, useCallback } from 'react';
import { createPortal } from 'react-dom';
import { cn } from '@/utils/helpers';
import { Button } from '../Button';
import styles from './Modal.module.scss';

export interface ModalProps {
  visible: boolean;
  title: string;
  width?: number;
  onClose: () => void;
  onConfirm?: () => void;
  confirmText?: string;
  cancelText?: string;
  loading?: boolean;
  footer?: ReactNode | null;
  closable?: boolean;
  maskClosable?: boolean;
  children: ReactNode;
}

export const Modal: FC<ModalProps> = ({
  visible,
  title,
  width = 520,
  onClose,
  onConfirm,
  confirmText = '确定',
  cancelText = '取消',
  loading = false,
  footer,
  closable = true,
  maskClosable = true,
  children,
}) => {
  const handleKeyDown = useCallback(
    (e: KeyboardEvent) => {
      if (e.key === 'Escape' && closable) {
        onClose();
      }
    },
    [closable, onClose]
  );

  useEffect(() => {
    if (visible) {
      document.addEventListener('keydown', handleKeyDown);
      document.body.style.overflow = 'hidden';
    }

    return () => {
      document.removeEventListener('keydown', handleKeyDown);
      document.body.style.overflow = '';
    };
  }, [visible, handleKeyDown]);

  const handleMaskClick = () => {
    if (maskClosable) {
      onClose();
    }
  };

  const renderFooter = () => {
    if (footer === null) return null;

    if (footer) return footer;

    return (
      <div className={styles.modal__footer}>
        <Button variant="outline" onClick={onClose} disabled={loading}>
          {cancelText}
        </Button>
        {onConfirm && (
          <Button variant="primary" onClick={onConfirm} loading={loading}>
            {confirmText}
          </Button>
        )}
      </div>
    );
  };

  if (!visible) return null;

  const modalContent = (
    <div className={styles.modal}>
      <div className={styles.modal__mask} onClick={handleMaskClick} />
      <div className={styles.modal__wrapper}>
        <div className={styles.modal__content} style={{ width }} onClick={(e) => e.stopPropagation()}>
          <div className={styles.modal__header}>
            <h3 className={styles.modal__title}>{title}</h3>
            {closable && (
              <button className={styles.modal__close} onClick={onClose} type="button">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                  <path d="M18 6L6 18M6 6l12 12" />
                </svg>
              </button>
            )}
          </div>
          <div className={styles.modal__body}>{children}</div>
          {renderFooter()}
        </div>
      </div>
    </div>
  );

  if (typeof document === 'undefined') return null;

  return createPortal(modalContent, document.body);
};
