import React, { useState, useEffect } from 'react';
import { Wifi, WifiOff } from 'lucide-react';
import { NetworkService } from '../services/networkService';

interface NetworkStatusProps {
  className?: string;
}

const NetworkStatus: React.FC<NetworkStatusProps> = ({ className = '' }) => {
  const [networkStatus, setNetworkStatus] = useState({
    isOnline: true,
    lastCheck: new Date()
  });

  const networkService = NetworkService.getInstance();

  useEffect(() => {
    // 初始化网络状态
    setNetworkStatus(networkService.getStatus());
    
    // 订阅网络状态变化
    const unsubscribe = networkService.subscribe((status) => {
      setNetworkStatus(status);
    });

    return () => {
      unsubscribe();
    };
  }, []);



  const getStatusColor = () => {
    return networkStatus.isOnline ? 'text-green-500' : 'text-orange-500';
  };

  const getStatusText = () => {
    return networkStatus.isOnline ? '在线' : '离线';
  };

  const getStatusIcon = () => {
    return networkStatus.isOnline ? <Wifi className="w-4 h-4" /> : <WifiOff className="w-4 h-4" />;
  };

  return (
    <div className={`flex items-center space-x-2 ${className}`}>
      {/* 状态指示器 */}
      <div className={`flex items-center space-x-1 ${getStatusColor()}`}>
        {getStatusIcon()}
        <span className="text-sm font-medium">{getStatusText()}</span>
      </div>

      {/* 详细信息提示 */}
      <div className="relative group">
        <div className="w-2 h-2 bg-blue-400 rounded-full cursor-help"></div>
        <div className="absolute bottom-full right-0 mb-2 w-48 p-3 bg-gray-800 text-white text-xs rounded-lg shadow-lg opacity-0 group-hover:opacity-100 transition-opacity z-50">
          <div className="space-y-1">
            <div>网络状态: {networkStatus.isOnline ? '在线' : '离线'}</div>
            <div>最后检查: {networkStatus.lastCheck ? networkStatus.lastCheck.toLocaleTimeString() : '未知'}</div>
          </div>
          <div className="absolute top-full right-4 w-0 h-0 border-l-4 border-r-4 border-t-4 border-transparent border-t-gray-800"></div>
        </div>
      </div>
    </div>
  );
};

export default NetworkStatus;