import { useEffect, useState } from 'react';
import { Card } from '../ui/card';
import { AlertCircle, CheckCircle2, Loader2, MapPin } from 'lucide-react';
import { Button } from '../ui/button';

interface MapStatus {
  provider: 'leaflet' | 'amap' | 'placeholder' | 'loading';
  message: string;
  isReady: boolean;
}

export function MapStatusIndicator() {
  const [status, setStatus] = useState<MapStatus>({
    provider: 'loading',
    message: '检测地图状态中...',
    isReady: false,
  });

  useEffect(() => {
    const checkMapStatus = () => {
      // 检查 Leaflet
      if (window.L) {
        setStatus({
          provider: 'leaflet',
          message: `Leaflet 地图已加载 (版本 ${window.L.version || '未知'})`,
          isReady: true,
        });
        return;
      }

      // 检查高德地图
      if (window.AMap) {
        setStatus({
          provider: 'amap',
          message: `高德地图已加载 (版本 ${window.AMap.version || '未知'})`,
          isReady: true,
        });
        return;
      }

      // 占位地图模式
      setStatus({
        provider: 'placeholder',
        message: '使用占位地图模式（演示模式）',
        isReady: true,
      });
    };

    // 立即检查
    checkMapStatus();

    // 设置定时器，持续检查（以防地图库稍后加载）
    const interval = setInterval(checkMapStatus, 1000);

    // 5秒后停止检查
    const timeout = setTimeout(() => {
      clearInterval(interval);
      if (status.provider === 'loading') {
        setStatus({
          provider: 'placeholder',
          message: '地图加载超时，使用占位地图模式',
          isReady: true,
        });
      }
    }, 5000);

    return () => {
      clearInterval(interval);
      clearTimeout(timeout);
    };
  }, []);

  const getIcon = () => {
    switch (status.provider) {
      case 'loading':
        return <Loader2 className="w-5 h-5 animate-spin text-blue-600" />;
      case 'leaflet':
      case 'amap':
        return <CheckCircle2 className="w-5 h-5 text-green-600" />;
      case 'placeholder':
        return <AlertCircle className="w-5 h-5 text-orange-600" />;
    }
  };

  const getStatusColor = () => {
    switch (status.provider) {
      case 'loading':
        return 'border-blue-200 bg-blue-50';
      case 'leaflet':
      case 'amap':
        return 'border-green-200 bg-green-50';
      case 'placeholder':
        return 'border-orange-200 bg-orange-50';
    }
  };

  const handleViewDocs = () => {
    // 在实际应用中，这里可以打开帮助文档
    console.log('查看地图配置文档');
    alert('请查看项目根目录下的以下文档：\n\n1. ENABLE_REAL_MAP.md - 快速启用指南\n2. MAP_CONFIGURATION_GUIDE.md - 完整配置指南\n3. MAP_STATUS_INDICATOR.md - 状态说明');
  };

  return (
    <Card className={`p-4 ${getStatusColor()} transition-colors`}>
      <div className="flex items-start gap-3">
        <div className="flex-shrink-0 mt-0.5">{getIcon()}</div>
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2 mb-1">
            <MapPin className="w-4 h-4" />
            <span className="font-medium text-sm">地图状态</span>
          </div>
          <p className="text-sm text-muted-foreground mb-2">{status.message}</p>
          
          {status.provider === 'placeholder' && (
            <div className="space-y-2">
              <p className="text-xs text-muted-foreground">
                💡 所有地图功能正常可用，只是显示演示界面而非真实地图
              </p>
              <div className="flex gap-2">
                <Button
                  size="sm"
                  variant="outline"
                  onClick={handleViewDocs}
                  className="text-xs h-7"
                >
                  查看启用指南
                </Button>
              </div>
            </div>
          )}

          {status.provider === 'loading' && (
            <p className="text-xs text-muted-foreground">
              正在尝试加载免费地图服务（Leaflet）...
            </p>
          )}

          {(status.provider === 'leaflet' || status.provider === 'amap') && (
            <p className="text-xs text-green-700">
              ✅ 真实地图已启用，可以查看卫星影像和街道地图
            </p>
          )}
        </div>
      </div>
    </Card>
  );
}
