'use client';

import { toast, type ToastT } from 'sonner';
import { 
  CheckCircle2, 
  XCircle, 
  AlertCircle, 
  Info, 
  Loader2
} from 'lucide-react';

/**
 * 全局消息提示工具
 * 对 sonner toast 进行封装，提供更简洁的 API
 */
class GlobalMessage {
  success(message: string, duration = 3000, options?: Partial<ToastT>) {
    toast.success(message, {
      icon: <CheckCircle2 className="h-4 w-4" />,
      duration,
      ...options,
    });
  }

  error(message: string, duration = 3000, options?: Partial<ToastT>) {
    toast.error(message, {
      icon: <XCircle className="h-4 w-4" />,
      duration,
      ...options,
    });
  }

  warning(message: string, duration = 3000, options?: Partial<ToastT>) {
    toast.warning(message, {
      icon: <AlertCircle className="h-4 w-4" />,
      duration,
      ...options,
    });
  }

  info(message: string, duration = 3000, options?: Partial<ToastT>) {
    toast(message, {
      icon: <Info className="h-4 w-4" />,
      duration,
      ...options,
    });
  }

  loading(message: string, options?: Partial<ToastT>) {
    return toast.promise(
      new Promise(() => {}),
      {
        loading: message,
        icon: <Loader2 className="h-4 w-4 animate-spin" />,
        ...options,
      }
    );
  }

  dismiss() {
    toast.dismiss();
  }
}

// 导出单例实例
export const msg = new GlobalMessage();

// 为了方便使用，也导出单独的方法
export const { success, error, warning, info, loading, dismiss } = msg;
// 在文件末尾添加全局注册方法
export function registerGlobalMessage() {
  if (typeof window !== 'undefined') {
    // 注册完整实例
    window.msg = msg;
    
    // 注册便捷方法
    window.$message = {
      success: msg.success.bind(msg),
      error: msg.error.bind(msg),
      warning: msg.warning.bind(msg),
      info: msg.info.bind(msg),
      loading: msg.loading.bind(msg),
      dismiss: msg.dismiss.bind(msg),
    };

    // 添加调试信息
    console.log('GlobalMessage registered:', {
      msg: window.msg,
      $message: window.$message
    });
  }
}
