import React, { useState, useEffect, useCallback, useRef } from 'react'

/** Toast 类型 */
export type ToastType = 'success' | 'error' | 'warning' | 'info'

/** 单条 Toast 数据 */
export interface ToastItem {
  id: string
  message: string
  type: ToastType
  duration: number
}

/** Toast 容器组件属性 */
interface ToastContainerProps {
  toasts: ToastItem[]
  onDismiss: (id: string) => void
}

/** 单条 Toast 组件 */
const SingleToast = React.memo(function SingleToast({
  toast,
  onDismiss
}: {
  toast: ToastItem
  onDismiss: (id: string) => void
}) {
  const [visible, setVisible] = useState(false)
  const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null)

  useEffect(() => {
    // 进入动画
    requestAnimationFrame(() => setVisible(true))

    // 自动消失
    if (toast.duration > 0) {
      timerRef.current = setTimeout(() => {
        setVisible(false)
        // 等待退出动画完成后再移除
        setTimeout(() => onDismiss(toast.id), 300)
      }, toast.duration)
    }

    return () => {
      if (timerRef.current) clearTimeout(timerRef.current)
    }
  }, [toast.id, toast.duration, onDismiss])

  const handleClose = useCallback(() => {
    if (timerRef.current) clearTimeout(timerRef.current)
    setVisible(false)
    setTimeout(() => onDismiss(toast.id), 300)
  }, [toast.id, onDismiss])

  const typeIcons: Record<ToastType, string> = {
    success: '✓',
    error: '✕',
    warning: '⚠',
    info: 'ℹ'
  }

  return (
    <div
      className={`toast-item toast-${toast.type} ${visible ? 'toast-visible' : ''}`}
      role="alert"
      aria-live="assertive"
    >
      <span className="toast-icon" aria-hidden="true">
        {typeIcons[toast.type]}
      </span>
      <span className="toast-message">{toast.message}</span>
      <button
        className="toast-close"
        onClick={handleClose}
        aria-label="关闭通知"
        type="button"
      >
        ✕
      </button>
    </div>
  )
})

/**
 * UX-05: Toast 容器组件
 * 支持多条堆叠、类型区分、关闭按钮和自动消失
 */
export const ToastContainer = React.memo(function ToastContainer({
  toasts,
  onDismiss
}: ToastContainerProps) {
  if (toasts.length === 0) return null

  return (
    <div className="toast-container" aria-label="通知区域">
      {toasts.map(toast => (
        <SingleToast key={toast.id} toast={toast} onDismiss={onDismiss} />
      ))}
    </div>
  )
})

ToastContainer.displayName = 'ToastContainer'
