import { useState, useCallback } from 'react'
import { ToastItem } from '../components/ToastContainer'

export interface ShowToastOptions {
  type?: 'success' | 'error' | 'warning' | 'info'
  title: string
  message?: string
  duration?: number
}

export const useToast = () => {
  const [toasts, setToasts] = useState<ToastItem[]>([])

  const showToast = useCallback((options: ShowToastOptions) => {
    const id = Date.now().toString() + Math.random().toString(36).substr(2, 9)
    const newToast: ToastItem = {
      id,
      type: options.type || 'info',
      title: options.title,
      message: options.message,
      duration: options.duration || 3000
    }

    setToasts(prev => [...prev, newToast])
    return id
  }, [])

  const removeToast = useCallback((id: string) => {
    setToasts(prev => prev.filter(toast => toast.id !== id))
  }, [])

  const clearAllToasts = useCallback(() => {
    setToasts([])
  }, [])

  // 便捷方法
  const showSuccess = useCallback((title: string, message?: string, duration?: number) => {
    return showToast({ type: 'success', title, message, duration })
  }, [showToast])

  const showError = useCallback((title: string, message?: string, duration?: number) => {
    return showToast({ type: 'error', title, message, duration })
  }, [showToast])

  const showWarning = useCallback((title: string, message?: string, duration?: number) => {
    console.log('showWarning调用:', { title, message, duration })
    return showToast({ type: 'warning', title, message, duration })
  }, [showToast])

  const showInfo = useCallback((title: string, message?: string, duration?: number) => {
    return showToast({ type: 'info', title, message, duration })
  }, [showToast])

  return {
    toasts,
    showToast,
    removeToast,
    clearAllToasts,
    showSuccess,
    showError,
    showWarning,
    showInfo
  }
}