import React from 'react'
import { View } from '@tarojs/components'
import './index.css'

interface PopupProps {
  visible?: boolean
  placement?: 'top' | 'bottom' | 'left' | 'right' | 'center'
  closeOnOverlayClick?: boolean
  showOverlay?: boolean
  zIndex?: number
  duration?: number
  closeBtn?: boolean
  onVisibleChange?: (visible: boolean, trigger: string) => void
  onClose?: () => void
  className?: string
  children?: React.ReactNode
}

export default function TDesignPopup({
  visible = false,
  placement = 'bottom',
  closeOnOverlayClick = true,
  showOverlay = true,
  zIndex = 11500,
  duration = 240,
  closeBtn = false,
  onVisibleChange,
  onClose,
  className = '',
  children
}: PopupProps) {
  const handleOverlayClick = () => {
    if (closeOnOverlayClick) {
      onVisibleChange?.(false, 'overlay')
      onClose?.()
    }
  }

  const handleClose = () => {
    onVisibleChange?.(false, 'close-btn')
    onClose?.()
  }

  if (!visible) {
    return null
  }

  return (
    <View className={`tdesign-popup-wrapper ${className}`} style={{ zIndex }}>
      {/* 遮罩层 */}
      {showOverlay && (
        <View
          className="tdesign-popup__overlay"
          onClick={handleOverlayClick}
        />
      )}

      {/* 弹窗内容 */}
      <View
        className={`tdesign-popup tdesign-popup--${placement}`}
        style={{
          transition: `all ${duration}ms ease`
        }}
      >
        {/* 关闭按钮 */}
        {closeBtn && (
          <View
            className="tdesign-popup__close"
            onClick={handleClose}
          >
            ✕
          </View>
        )}

        {/* 内容区域 */}
        <View className="tdesign-popup__content">
          {children}
        </View>
      </View>
    </View>
  )
}