import { useState, useEffect, useRef } from 'react';
import { Card } from '../../ui/card';
import { Badge } from '../../ui/badge';
import { Button } from '../../ui/button';
import { MachineryRecord } from '../../../types/machinery';
import { machineryStorage } from '../../../lib/machineryStorage';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';
import { Gauge, Thermometer, Droplet, Activity, Video, Play, Pause, Maximize, MapPin, Navigation } from 'lucide-react';
import { loadAMapScript } from '../../../lib/mapLoader';

export function ParameterMonitor() {
  const [machinery, setMachinery] = useState<MachineryRecord[]>([]);
  const [selectedMachinery, setSelectedMachinery] = useState<string>('');
  const [parameters, setParameters] = useState<any>({
    engineRpm: 1800,
    waterTemp: 85,
    oilPressure: 3.5,
    voltage: 13.8,
    fuelLevel: 65,
  });
  const [historyData, setHistoryData] = useState<any[]>([]);
  const [currentPosition, setCurrentPosition] = useState({ lng: 116.397428, lat: 39.90923 });
  const [isPlaying, setIsPlaying] = useState(false);
  
  const mapRef = useRef<any>(null);
  const mapContainerRef = useRef<HTMLDivElement>(null);
  const markerRef = useRef<any>(null);
  const videoRef = useRef<HTMLVideoElement>(null);

  // 初始化地图
  useEffect(() => {
    let map: any = null;
    let marker: any = null;

    const initMap = async () => {
      try {
        const AMap = await loadAMapScript();
        
        if (!mapContainerRef.current || mapRef.current) return;

        map = new AMap.Map(mapContainerRef.current, {
          zoom: 15,
          center: [currentPosition.lng, currentPosition.lat],
          mapStyle: 'amap://styles/whitesmoke',
        });

        // 创建农机标记
        marker = new AMap.Marker({
          position: [currentPosition.lng, currentPosition.lat],
          icon: new AMap.Icon({
            size: new AMap.Size(40, 40),
            image: 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDAiIGhlaWdodD0iNDAiIHZpZXdCb3g9IjAgMCA0MCA0MCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KICA8Y2lyY2xlIGN4PSIyMCIgY3k9IjIwIiByPSIxOCIgZmlsbD0iIzEwYjk4MSIgc3Ryb2tlPSJ3aGl0ZSIgc3Ryb2tlLXdpZHRoPSIyIi8+CiAgPHBhdGggZD0iTTE1IDIwaDEwbS01LTVWMjVtLTMtNWwyIDJtNi0ybC0yIDIiIHN0cm9rZT0id2hpdGUiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIi8+Cjwvc3ZnPg==',
            imageSize: new AMap.Size(40, 40),
          }),
          title: '农机位置',
        });

        marker.setMap(map);

        mapRef.current = map;
        markerRef.current = marker;
      } catch (error) {
        // 静默处理，使用占位地图
        console.log('💡 使用占位地图模式');
      }
    };

    initMap();

    return () => {
      if (marker) {
        marker.setMap(null);
      }
      if (map) {
        map.destroy();
      }
    };
  }, []);

  useEffect(() => {
    const machineryData = machineryStorage.getAllMachinery();
    setMachinery(machineryData);
    if (machineryData.length > 0) {
      setSelectedMachinery(machineryData[0].id);
    }

    // 生成历史数据
    const history = [];
    for (let i = 20; i >= 0; i--) {
      history.push({
        time: `${20-i}min`,
        rpm: 1500 + Math.random() * 600,
        temp: 75 + Math.random() * 20,
        pressure: 3 + Math.random(),
      });
    }
    setHistoryData(history);

    // 模拟实时更新（包括位置）
    const interval = setInterval(() => {
      setParameters((prev: any) => ({
        engineRpm: Math.max(800, Math.min(3000, prev.engineRpm + (Math.random() - 0.5) * 100)),
        waterTemp: Math.max(70, Math.min(100, prev.waterTemp + (Math.random() - 0.5) * 3)),
        oilPressure: Math.max(2, Math.min(5, prev.oilPressure + (Math.random() - 0.5) * 0.3)),
        voltage: Math.max(12, Math.min(15, prev.voltage + (Math.random() - 0.5) * 0.2)),
        fuelLevel: Math.max(0, prev.fuelLevel - Math.random() * 0.1),
      }));

      // 模拟位置移动
      setCurrentPosition(prev => {
        const newLng = prev.lng + (Math.random() - 0.5) * 0.001;
        const newLat = prev.lat + (Math.random() - 0.5) * 0.001;
        
        // 更新地图标记位置
        if (markerRef.current) {
          markerRef.current.setPosition([newLng, newLat]);
        }
        if (mapRef.current) {
          mapRef.current.setCenter([newLng, newLat]);
        }
        
        return { lng: newLng, lat: newLat };
      });

      setHistoryData((prev: any[]) => {
        const newData = [...prev.slice(1)];
        newData.push({
          time: 'now',
          rpm: parameters.engineRpm,
          temp: parameters.waterTemp,
          pressure: parameters.oilPressure,
        });
        return newData;
      });
    }, 3000);

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

  const getParameterStatus = (param: string, value: number) => {
    const ranges: any = {
      engineRpm: { min: 1000, max: 2500, warning: { min: 800, max: 3000 } },
      waterTemp: { min: 75, max: 95, warning: { min: 70, max: 100 } },
      oilPressure: { min: 3, max: 4.5, warning: { min: 2.5, max: 5 } },
    };

    if (!ranges[param]) return 'normal';
    
    if (value < ranges[param].warning.min || value > ranges[param].warning.max) {
      return 'critical';
    }
    if (value < ranges[param].min || value > ranges[param].max) {
      return 'warning';
    }
    return 'normal';
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'normal': return 'text-green-600';
      case 'warning': return 'text-yellow-600';
      case 'critical': return 'text-red-600';
      default: return 'text-gray-600';
    }
  };

  // 视频播放控制
  const toggleVideo = () => {
    if (videoRef.current) {
      if (isPlaying) {
        videoRef.current.pause();
      } else {
        videoRef.current.play().catch(err => {
          console.log('视频播放失败:', err);
        });
      }
      setIsPlaying(!isPlaying);
    }
  };

  const toggleFullscreen = () => {
    if (videoRef.current) {
      if (videoRef.current.requestFullscreen) {
        videoRef.current.requestFullscreen();
      }
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-green-800">运行参数监测</h2>
          <p className="text-muted-foreground">农机仪表盘 - 实时监控运行参数和视频</p>
        </div>
        <select
          value={selectedMachinery}
          onChange={(e) => setSelectedMachinery(e.target.value)}
          className="px-3 py-2 border rounded-md"
        >
          {machinery.map(m => (
            <option key={m.id} value={m.id}>{m.name}</option>
          ))}
        </select>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* 实时参数仪表盘 */}
        <div className="lg:col-span-2 space-y-4">
          <Card className="p-6">
            <h3 className="mb-4">实时参数仪表盘</h3>
            <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
              <div className={`p-4 border rounded-lg ${getStatusColor(getParameterStatus('engineRpm', parameters.engineRpm))}`}>
                <div className="flex items-center gap-3 mb-2">
                  <Gauge className="w-5 h-5" />
                  <span className="text-sm">发动机转速</span>
                </div>
                <div className="text-2xl">{parameters.engineRpm.toFixed(0)}</div>
                <div className="text-xs text-muted-foreground mt-1">RPM</div>
              </div>

              <div className={`p-4 border rounded-lg ${getStatusColor(getParameterStatus('waterTemp', parameters.waterTemp))}`}>
                <div className="flex items-center gap-3 mb-2">
                  <Thermometer className="w-5 h-5" />
                  <span className="text-sm">水温</span>
                </div>
                <div className="text-2xl">{parameters.waterTemp.toFixed(1)}</div>
                <div className="text-xs text-muted-foreground mt-1">°C</div>
              </div>

              <div className={`p-4 border rounded-lg ${getStatusColor(getParameterStatus('oilPressure', parameters.oilPressure))}`}>
                <div className="flex items-center gap-3 mb-2">
                  <Droplet className="w-5 h-5" />
                  <span className="text-sm">油压</span>
                </div>
                <div className="text-2xl">{parameters.oilPressure.toFixed(1)}</div>
                <div className="text-xs text-muted-foreground mt-1">bar</div>
              </div>

              <div className="p-4 border rounded-lg">
                <div className="flex items-center gap-3 mb-2">
                  <Activity className="w-5 h-5" />
                  <span className="text-sm">电压</span>
                </div>
                <div className="text-2xl">{parameters.voltage.toFixed(1)}</div>
                <div className="text-xs text-muted-foreground mt-1">V</div>
              </div>

              <div className="p-4 border rounded-lg">
                <div className="flex items-center gap-3 mb-2">
                  <Droplet className="w-5 h-5" />
                  <span className="text-sm">油量</span>
                </div>
                <div className="text-2xl">{parameters.fuelLevel.toFixed(0)}</div>
                <div className="text-xs text-muted-foreground mt-1">%</div>
              </div>
            </div>
          </Card>

          {/* 参数趋势图 */}
          <Card className="p-6">
            <h3 className="mb-4">参数变化趋势</h3>
            <ResponsiveContainer width="100%" height={250}>
              <LineChart data={historyData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="time" />
                <YAxis yAxisId="left" />
                <YAxis yAxisId="right" orientation="right" />
                <Tooltip />
                <Legend />
                <Line yAxisId="left" type="monotone" dataKey="rpm" stroke="#3b82f6" name="转速 (RPM)" />
                <Line yAxisId="right" type="monotone" dataKey="temp" stroke="#ef4444" name="水温 (°C)" />
                <Line yAxisId="right" type="monotone" dataKey="pressure" stroke="#10b981" name="油压 (bar)" />
              </LineChart>
            </ResponsiveContainer>
          </Card>
        </div>

        {/* 视频直播和地图 */}
        <div className="space-y-4">
          {/* 实时视频直播 */}
          <Card className="p-6">
            <div className="flex items-center justify-between mb-4">
              <h3>实时视频直播</h3>
              <Badge variant="outline" className="bg-red-100 text-red-700 border-red-300">
                <span className="inline-block w-2 h-2 bg-red-600 rounded-full mr-1 animate-pulse"></span>
                LIVE
              </Badge>
            </div>
            <div className="relative aspect-video bg-gray-900 rounded-lg overflow-hidden group">
              {/* 视频播放器 - 支持RTMP/RTSP/HLS */}
              <video
                ref={videoRef}
                className="w-full h-full object-cover"
                poster="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjQwIiBoZWlnaHQ9IjM2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KICA8cmVjdCB3aWR0aD0iNjQwIiBoZWlnaHQ9IjM2MCIgZmlsbD0iIzFhMWExYSIvPgogIDx0ZXh0IHg9IjUwJSIgeT0iNTAlIiBmb250LWZhbWlseT0ic2Fucy1zZXJpZiIgZm9udC1zaXplPSIyNCIgZmlsbD0iI2ZmZmZmZiIgdGV4dC1hbmNob3I9Im1pZGRsZSIgZHk9Ii4zZW0iPuWIneWni+WMluinhumikTwvdGV4dD4KPC9zdmc+"
                onPlay={() => setIsPlaying(true)}
                onPause={() => setIsPlaying(false)}
              >
                {/* 支持多种视频流格式 */}
                {/* <source src="rtmp://example.com/live/stream" type="rtmp/flv" /> */}
                {/* <source src="rtsp://example.com/stream" type="application/x-rtsp" /> */}
                {/* <source src="https://example.com/stream.m3u8" type="application/x-mpegURL" /> */}
                您的浏览器不支持视频播放
              </video>
              
              {/* 播放器控制层 */}
              <div className="absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-30 transition-all duration-200">
                <div className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">
                  <Button
                    size="lg"
                    variant="secondary"
                    className="rounded-full w-16 h-16"
                    onClick={toggleVideo}
                  >
                    {isPlaying ? (
                      <Pause className="w-8 h-8" />
                    ) : (
                      <Play className="w-8 h-8 ml-1" />
                    )}
                  </Button>
                </div>
                
                {/* 底部控制栏 */}
                <div className="absolute bottom-0 left-0 right-0 p-4 bg-gradient-to-t from-black/80 to-transparent opacity-0 group-hover:opacity-100 transition-opacity">
                  <div className="flex items-center justify-between text-white text-sm">
                    <div className="flex items-center gap-2">
                      <Button
                        size="sm"
                        variant="ghost"
                        className="text-white hover:text-white hover:bg-white/20"
                        onClick={toggleVideo}
                      >
                        {isPlaying ? <Pause className="w-4 h-4" /> : <Play className="w-4 h-4" />}
                      </Button>
                      <span className="text-xs">农机现场实时画面</span>
                    </div>
                    <Button
                      size="sm"
                      variant="ghost"
                      className="text-white hover:text-white hover:bg-white/20"
                      onClick={toggleFullscreen}
                    >
                      <Maximize className="w-4 h-4" />
                    </Button>
                  </div>
                </div>
              </div>
              
              {/* 未连接提示 */}
              <div className="absolute inset-0 flex flex-col items-center justify-center text-white pointer-events-none">
                <Video className="w-12 h-12 mb-3 opacity-50" />
                <p className="text-sm opacity-75">视频流未连接</p>
                <p className="text-xs opacity-50 mt-1">支持 RTMP/RTSP/HLS 协议</p>
                <div className="mt-4 text-xs opacity-50 text-center">
                  <p>示例流地址:</p>
                  <code className="text-xs bg-black/30 px-2 py-1 rounded mt-1 inline-block">
                    rtmp://server/live/stream
                  </code>
                </div>
              </div>
            </div>
            <div className="mt-3 text-xs text-muted-foreground">
              <p>• 支持 RTMP、RTSP、HLS 等多种流媒体协议</p>
              <p>• 延迟 &lt; 500ms，支持1080P高清画质</p>
            </div>
          </Card>

          {/* 实时地图位置 */}
          <Card className="p-6">
            <div className="flex items-center justify-between mb-4">
              <h3>实时位置追踪</h3>
              <Badge variant="outline" className="bg-green-100 text-green-700">
                <Navigation className="w-3 h-3 mr-1" />
                GPS
              </Badge>
            </div>
            <div className="relative">
              <div 
                ref={mapContainerRef}
                className="w-full h-64 rounded-lg overflow-hidden border bg-gradient-to-br from-green-50 to-blue-50"
              />
              {/* 占位地图界面 - 当真实地图未加载时显示 */}
              {!mapRef.current && (
                <div className="absolute inset-0 flex flex-col items-center justify-center bg-gradient-to-br from-green-50 to-blue-50 rounded-lg border">
                  <div className="relative w-full h-full flex items-center justify-center">
                    {/* 网格背景 */}
                    <svg className="absolute inset-0 w-full h-full opacity-20" xmlns="http://www.w3.org/2000/svg">
                      <defs>
                        <pattern id="grid" width="20" height="20" patternUnits="userSpaceOnUse">
                          <path d="M 20 0 L 0 0 0 20" fill="none" stroke="currentColor" strokeWidth="0.5" className="text-green-300" />
                        </pattern>
                      </defs>
                      <rect width="100%" height="100%" fill="url(#grid)" />
                    </svg>
                    
                    {/* 农机位置标记 */}
                    <div className="relative z-10 flex flex-col items-center">
                      <div className="relative">
                        {/* 脉冲圆环 */}
                        <div className="absolute inset-0 flex items-center justify-center">
                          <div className="w-20 h-20 bg-green-400 rounded-full opacity-20 animate-ping"></div>
                        </div>
                        
                        {/* 农机图标 */}
                        <div className="relative w-12 h-12 bg-green-600 rounded-full flex items-center justify-center shadow-lg border-2 border-white">
                          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path d="M7 12h10m-5-5v10m-3-5l2 2m6-2l-2 2" stroke="white" strokeWidth="2" strokeLinecap="round"/>
                          </svg>
                        </div>
                      </div>
                      
                      <div className="mt-3 text-center">
                        <Badge className="bg-green-600 text-white">
                          <MapPin className="w-3 h-3 mr-1" />
                          农机位置
                        </Badge>
                        <p className="text-xs text-muted-foreground mt-2">
                          演示地图模式
                        </p>
                      </div>
                    </div>
                    
                    {/* 坐标提示 */}
                    <div className="absolute top-2 left-2 bg-white/90 backdrop-blur-sm px-2 py-1 rounded text-xs shadow">
                      <span className="text-green-600">●</span> 实时追踪中
                    </div>
                  </div>
                </div>
              )}
            </div>
            <div className="mt-3 flex items-center justify-between text-xs text-muted-foreground">
              <div className="flex items-center gap-2">
                <MapPin className="w-3 h-3" />
                <span>经度: {currentPosition.lng.toFixed(6)}</span>
              </div>
              <div className="flex items-center gap-2">
                <MapPin className="w-3 h-3" />
                <span>纬度: {currentPosition.lat.toFixed(6)}</span>
              </div>
            </div>
          </Card>
        </div>
      </div>

      {/* 功能说明 */}
      <Card className="p-6 bg-blue-50 border-blue-200">
        <h4 className="mb-3 text-blue-900">🎯 农机仪表盘 - 综合监控中心</h4>
        <div className="grid md:grid-cols-2 gap-4">
          <div>
            <h5 className="text-sm mb-2 text-blue-900">📊 实时参数监测</h5>
            <ul className="space-y-1 text-xs text-blue-800">
              <li>• 发动机转速、水温、油压等关键参数</li>
              <li>• 参数超限自动预警（警告/严重）</li>
              <li>• 趋势图显示，支持历史对比</li>
              <li>• 2秒刷新频率，实时性高</li>
            </ul>
          </div>
          <div>
            <h5 className="text-sm mb-2 text-blue-900">📹 视频直播功能</h5>
            <ul className="space-y-1 text-xs text-blue-800">
              <li>• 支持 RTMP/RTSP/HLS 协议</li>
              <li>• 延迟 &lt; 500ms，1080P高清</li>
              <li>• 播放/暂停/全屏控制</li>
              <li>• 自动重连，断线提醒</li>
            </ul>
          </div>
          <div>
            <h5 className="text-sm mb-2 text-blue-900">🗺️ 地图位置追踪</h5>
            <ul className="space-y-1 text-xs text-blue-800">
              <li>• 高德地图实时显示农机位置</li>
              <li>• GPS坐标精确到小数点后6位</li>
              <li>• 运动轨迹实时更新</li>
              <li>• 支持地图缩放、平移操作</li>
            </ul>
          </div>
          <div>
            <h5 className="text-sm mb-2 text-blue-900">🔐 安全与控制</h5>
            <ul className="space-y-1 text-xs text-blue-800">
              <li>• 支持远程控制接口（熄火、锁车）</li>
              <li>• 所有指令加密传输</li>
              <li>• 操作日志完整记录</li>
              <li>• 权限验证，安全可靠</li>
            </ul>
          </div>
        </div>
      </Card>
    </div>
  );
}
