import { useState, useEffect, useRef } from 'react';
import { Card } from '../../ui/card';
import { Badge } from '../../ui/badge';
import { Button } from '../../ui/button';
import { Input } from '../../ui/input';
import { Label } from '../../ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../../ui/select';
import { Slider } from '../../ui/slider';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../../ui/tabs';
import { Alert, AlertDescription } from '../../ui/alert';
import { 
  Play, Pause, RotateCcw, FastForward, MapPin, 
  Activity
} from 'lucide-react';
import { MachineryRecord } from '../../../types/machinery';
import { machineryStorage } from '../../../lib/machineryStorage';
import { loadAMapScript, isAMapLoaded } from '../../../lib/mapLoader';
import { toast } from 'sonner@2.0.3';

// 轨迹点数据类型
interface TrackPoint {
  id: string;
  timestamp: string;
  latitude: number;
  longitude: number;
  speed: number; // km/h
  heading: number; // 度
  workingWidth: number; // 米
  workingDepth?: number; // cm
  area: number; // 累计作业面积（亩）
  fuelConsumption: number; // 累计油耗（升）
  isWorking: boolean; // 是否在作业
}



// 高德地图类型声明
declare global {
  interface Window {
    AMap: any;
    _AMapSecurityConfig: any;
  }
}

export function TrackPlayback() {
  // 数据状态
  const [machinery, setMachinery] = useState<MachineryRecord[]>([]);
  const [selectedMachineryId, setSelectedMachineryId] = useState<string>('');
  const [selectedDate, setSelectedDate] = useState<string>(new Date().toISOString().split('T')[0]);
  const [trackData, setTrackData] = useState<TrackPoint[]>([]);
  
  // 播放控制状态
  const [isPlaying, setIsPlaying] = useState(false);
  const [currentIndex, setCurrentIndex] = useState(0);
  const [playSpeed, setPlaySpeed] = useState(1); // 1x, 2x, 4x, 8x
  const [showTrail, setShowTrail] = useState(true);
  
  // 地图状态
  const mapContainerRef = useRef<HTMLDivElement>(null);
  const mapRef = useRef<any>(null);
  const markerRef = useRef<any>(null);
  const polylineRef = useRef<any>(null);
  const trailPolylineRef = useRef<any>(null);
  const [isMapLoaded, setIsMapLoaded] = useState(false);
  
  // 播放定时器
  const playIntervalRef = useRef<NodeJS.Timeout | null>(null);

  // 加载数据
  useEffect(() => {
    loadMachinery();
    initializeMap();

    return () => {
      stopPlayback();
      if (mapRef.current) {
        mapRef.current.destroy();
      }
    };
  }, []);

  // 加载农机列表
  const loadMachinery = () => {
    const machineryData = machineryStorage.getAllMachinery();
    setMachinery(machineryData);
    
    // 默认选择第一台农机
    if (machineryData.length > 0) {
      setSelectedMachineryId(machineryData[0].id);
    }
  };

  // 初始化地图
  const initializeMap = () => {
    if (!isAMapLoaded()) {
      loadAMapScript()
        .then(() => {
          createMap();
        })
        .catch(() => {
          // 静默失败
        });
    } else {
      createMap();
    }
  };

  // 创建地图
  const createMap = () => {
    if (!mapContainerRef.current || !window.AMap) return;

    try {
      const map = new window.AMap.Map(mapContainerRef.current, {
        zoom: 15,
        center: [117.1201, 36.6512],
        mapStyle: 'amap://styles/normal',
      });

      mapRef.current = map;
      setIsMapLoaded(true);
    } catch (error) {
      console.log('ℹ️ 使用占位地图模式');
      setIsMapLoaded(true);
    }
  };

  // 加载轨迹数据
  const loadTrackData = () => {
    if (!selectedMachineryId || !selectedDate) {
      toast.error('请选择农机和日期');
      return;
    }

    // 生成模拟轨迹数据
    const startTime = new Date(`${selectedDate}T08:00:00`);
    const points: TrackPoint[] = [];
    const totalPoints = 200;
    
    // 起始位置
    let lat = 36.6512;
    let lng = 117.1201;
    let cumulativeArea = 0;
    let cumulativeFuel = 0;

    for (let i = 0; i < totalPoints; i++) {
      const timestamp = new Date(startTime.getTime() + i * 60 * 1000); // 每分钟一个点
      const isWorking = i > 10 && i < totalPoints - 10 && Math.random() > 0.1;
      const speed = isWorking ? 5 + Math.random() * 3 : Math.random() * 2;
      const heading = 45 + Math.sin(i * 0.1) * 30;
      
      // 模拟移动路径（矩形田块来回作业）
      const progress = i / totalPoints;
      if (progress < 0.25) {
        lng += 0.0001;
      } else if (progress < 0.5) {
        lat += 0.0001;
      } else if (progress < 0.75) {
        lng -= 0.0001;
      } else {
        lat -= 0.0001;
      }
      
      // 添加随机偏移
      lat += (Math.random() - 0.5) * 0.00005;
      lng += (Math.random() - 0.5) * 0.00005;
      
      // 计算作业面积和油耗
      if (isWorking) {
        cumulativeArea += 0.05; // 每次增加0.05亩
        cumulativeFuel += 0.02; // 每次增加0.02升
      }

      points.push({
        id: `point-${i}`,
        timestamp: timestamp.toISOString(),
        latitude: lat,
        longitude: lng,
        speed: Number(speed.toFixed(1)),
        heading: Number(heading.toFixed(1)),
        workingWidth: 2.5,
        workingDepth: isWorking ? 25 : 0,
        area: Number(cumulativeArea.toFixed(2)),
        fuelConsumption: Number(cumulativeFuel.toFixed(2)),
        isWorking
      });
    }

    setTrackData(points);
    setCurrentIndex(0);

    // 绘制轨迹到地图
    if (isMapLoaded && points.length > 0) {
      drawTrackOnMap(points);
    }

    toast.success(`已加载 ${points.length} 个轨迹点`);
  };

  // 在地图上绘制轨迹
  const drawTrackOnMap = (points: TrackPoint[]) => {
    if (!mapRef.current || !window.AMap) return;

    // 清除旧的轨迹
    if (polylineRef.current) {
      mapRef.current.remove(polylineRef.current);
    }
    if (markerRef.current) {
      mapRef.current.remove(markerRef.current);
    }

    // 绘制完整轨迹路径
    const path = points.map(p => [p.longitude, p.latitude]);
    const polyline = new window.AMap.Polyline({
      path: path,
      strokeColor: '#1890ff',
      strokeWeight: 4,
      strokeOpacity: 0.3,
    });
    polylineRef.current = polyline;
    polyline.setMap(mapRef.current);

    // 创建农机标记
    const marker = new window.AMap.Marker({
      position: [points[0].longitude, points[0].latitude],
      icon: new window.AMap.Icon({
        image: 'data:image/svg+xml;base64,' + btoa(`
          <svg width="40" height="40" xmlns="http://www.w3.org/2000/svg">
            <circle cx="20" cy="20" r="18" fill="#22c55e" stroke="#fff" stroke-width="3"/>
            <text x="20" y="27" font-size="20" text-anchor="middle" fill="#fff">🚜</text>
          </svg>
        `),
        size: new window.AMap.Size(40, 40),
        imageSize: new window.AMap.Size(40, 40)
      }),
      offset: new window.AMap.Pixel(-20, -20),
      angle: points[0].heading,
    });
    markerRef.current = marker;
    marker.setMap(mapRef.current);

    // 调整地图视野
    mapRef.current.setFitView();
  };

  // 播放控制
  const startPlayback = () => {
    if (trackData.length === 0) {
      toast.error('请先加载轨迹数据');
      return;
    }

    setIsPlaying(true);
    
    const interval = 1000 / playSpeed; // 根据速度调整间隔
    
    playIntervalRef.current = setInterval(() => {
      setCurrentIndex(prev => {
        if (prev >= trackData.length - 1) {
          stopPlayback();
          return prev;
        }
        
        const nextIndex = prev + 1;
        updateMapPosition(nextIndex);
        return nextIndex;
      });
    }, interval);
  };

  const pausePlayback = () => {
    setIsPlaying(false);
    if (playIntervalRef.current) {
      clearInterval(playIntervalRef.current);
      playIntervalRef.current = null;
    }
  };

  const stopPlayback = () => {
    pausePlayback();
    setCurrentIndex(0);
    if (trackData.length > 0) {
      updateMapPosition(0);
    }
  };

  const togglePlayback = () => {
    if (isPlaying) {
      pausePlayback();
    } else {
      startPlayback();
    }
  };

  // 更新地图上的位置
  const updateMapPosition = (index: number) => {
    if (!markerRef.current || !trackData[index]) return;

    const point = trackData[index];
    const position = [point.longitude, point.latitude];
    
    // 更新标记位置和角度
    markerRef.current.setPosition(position);
    markerRef.current.setAngle(point.heading);

    // 绘制已走过的轨迹
    if (showTrail && trailPolylineRef.current) {
      mapRef.current.remove(trailPolylineRef.current);
    }
    
    if (showTrail) {
      const trailPath = trackData.slice(0, index + 1).map(p => [p.longitude, p.latitude]);
      const trailPolyline = new window.AMap.Polyline({
        path: trailPath,
        strokeColor: '#22c55e',
        strokeWeight: 6,
        strokeOpacity: 0.8,
      });
      trailPolylineRef.current = trailPolyline;
      trailPolyline.setMap(mapRef.current);
    }

    // 地图跟随
    mapRef.current.setCenter(position);
  };

  // 手动拖动进度
  const handleProgressChange = (value: number[]) => {
    const newIndex = value[0];
    setCurrentIndex(newIndex);
    updateMapPosition(newIndex);
  };

  // 切换播放速度
  const cyclePlaySpeed = () => {
    const speeds = [1, 2, 4, 8];
    const currentSpeedIndex = speeds.indexOf(playSpeed);
    const nextSpeed = speeds[(currentSpeedIndex + 1) % speeds.length];
    setPlaySpeed(nextSpeed);
    
    // 如果正在播放，重启以应用新速度
    if (isPlaying) {
      pausePlayback();
      setTimeout(() => startPlayback(), 100);
    }
  };

  // 切换播放速度时重新启动
  useEffect(() => {
    if (isPlaying) {
      pausePlayback();
      setTimeout(() => startPlayback(), 100);
    }
  }, [playSpeed]);

  // 获取当前点数据
  const currentPoint = trackData[currentIndex];

  // 计算统计数据
  const stats = trackData.length > 0 ? {
    totalPoints: trackData.length,
    totalDistance: (trackData.length * 0.05).toFixed(2), // 估算距离（km）
    totalArea: trackData[trackData.length - 1]?.area || 0,
    totalFuel: trackData[trackData.length - 1]?.fuelConsumption || 0,
    avgSpeed: (trackData.reduce((sum, p) => sum + p.speed, 0) / trackData.length).toFixed(1),
    workingTime: (trackData.filter(p => p.isWorking).length / 60).toFixed(1), // 小时
  } : null;

  return (
    <div className="space-y-6">
      {/* 标题栏 */}
      <div>
        <h2 className="text-green-800">农机作业轨迹回放</h2>
        <p className="text-muted-foreground">查看历史作业轨迹，分析作业规范性</p>
      </div>

      {/* 选择器 */}
      <Card className="p-6">
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div>
            <Label>选择农机</Label>
            <Select value={selectedMachineryId} onValueChange={setSelectedMachineryId}>
              <SelectTrigger>
                <SelectValue placeholder="请选择农机" />
              </SelectTrigger>
              <SelectContent>
                {machinery.map(m => (
                  <SelectItem key={m.id} value={m.id}>
                    {m.name} - {m.model}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div>
            <Label>选择日期</Label>
            <Input
              type="date"
              value={selectedDate}
              onChange={(e) => setSelectedDate(e.target.value)}
            />
          </div>

          <div className="flex items-end">
            <Button onClick={loadTrackData} className="w-full">
              <Activity className="w-4 h-4 mr-2" />
              加载轨迹
            </Button>
          </div>
        </div>
      </Card>

      {/* 主内容区 */}
      <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">
            <div className="flex items-center justify-between mb-4">
              <h3>轨迹地图</h3>
              <div className="flex gap-2">
                <Button
                  variant={showTrail ? 'default' : 'outline'}
                  size="sm"
                  onClick={() => setShowTrail(!showTrail)}
                >
                  {showTrail ? '已走轨迹' : '完整轨迹'}
                </Button>
              </div>
            </div>
            
            <div 
              ref={mapContainerRef}
              className="h-[500px] bg-gradient-to-br from-green-50 to-blue-50 rounded-lg border-2 border-dashed relative"
            >
              {!isMapLoaded && (
                <div className="absolute inset-0 flex items-center justify-center">
                  <div className="text-center">
                    <MapPin className="w-12 h-12 mx-auto mb-3 text-green-600 animate-pulse" />
                    <p className="text-sm text-muted-foreground">加载地图中...</p>
                  </div>
                </div>
              )}
            </div>
          </Card>

          {/* 播放控制器 */}
          <Card className="p-6">
            <div className="space-y-4">
              {/* 播放按钮 */}
              <div className="flex items-center justify-center gap-3">
                <Button
                  variant="outline"
                  size="sm"
                  onClick={stopPlayback}
                  disabled={trackData.length === 0}
                >
                  <RotateCcw className="w-4 h-4" />
                </Button>
                
                <Button
                  onClick={togglePlayback}
                  disabled={trackData.length === 0}
                  className="w-24"
                >
                  {isPlaying ? (
                    <>
                      <Pause className="w-4 h-4 mr-2" />
                      暂停
                    </>
                  ) : (
                    <>
                      <Play className="w-4 h-4 mr-2" />
                      播放
                    </>
                  )}
                </Button>
                
                <Button
                  variant="outline"
                  size="sm"
                  onClick={cyclePlaySpeed}
                  disabled={trackData.length === 0}
                >
                  <FastForward className="w-4 h-4 mr-2" />
                  {playSpeed}x
                </Button>
              </div>

              {/* 进度条 */}
              <div className="space-y-2">
                <Slider
                  value={[currentIndex]}
                  max={Math.max(0, trackData.length - 1)}
                  step={1}
                  onValueChange={handleProgressChange}
                  disabled={trackData.length === 0}
                />
                
                <div className="flex justify-between text-xs text-muted-foreground">
                  <span>
                    {currentPoint ? new Date(currentPoint.timestamp).toLocaleTimeString('zh-CN') : '--:--:--'}
                  </span>
                  <span>
                    {currentIndex + 1} / {trackData.length}
                  </span>
                  <span>
                    {trackData.length > 0 ? 
                      new Date(trackData[trackData.length - 1].timestamp).toLocaleTimeString('zh-CN') : 
                      '--:--:--'
                    }
                  </span>
                </div>
              </div>
            </div>
          </Card>
        </div>

        {/* 右侧参数面板 */}
        <div className="space-y-4">
          {/* 实时参数 */}
          {currentPoint && (
            <Card className="p-4 bg-green-50 border-green-200">
              <h4 className="mb-3 text-green-900">实时参数</h4>
              <div className="space-y-3 text-sm">
                <div className="flex justify-between">
                  <span className="text-muted-foreground">当前速度</span>
                  <span className="font-medium">{currentPoint.speed} km/h</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">作业深度</span>
                  <span className="font-medium">{currentPoint.workingDepth} cm</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">作业宽度</span>
                  <span className="font-medium">{currentPoint.workingWidth} m</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">累计面积</span>
                  <span className="font-medium text-green-600">{currentPoint.area} 亩</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">累计油耗</span>
                  <span className="font-medium">{currentPoint.fuelConsumption} L</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">作业状态</span>
                  <Badge variant={currentPoint.isWorking ? 'default' : 'secondary'}>
                    {currentPoint.isWorking ? '作业中' : '空行'}
                  </Badge>
                </div>
              </div>
            </Card>
          )}

          {/* 作业统计 */}
          {stats && (
            <Card className="p-4">
              <h4 className="mb-3">作业统计</h4>
              <div className="space-y-3 text-sm">
                <div className="flex justify-between">
                  <span className="text-muted-foreground">总里程</span>
                  <span className="font-medium">{stats.totalDistance} km</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">作业面积</span>
                  <span className="font-medium text-green-600">{stats.totalArea} 亩</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">总油耗</span>
                  <span className="font-medium">{stats.totalFuel} L</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">平均速度</span>
                  <span className="font-medium">{stats.avgSpeed} km/h</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">作业时长</span>
                  <span className="font-medium">{stats.workingTime} h</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">油耗率</span>
                  <span className="font-medium">
                    {(stats.totalFuel / stats.totalArea).toFixed(2)} L/亩
                  </span>
                </div>
              </div>
            </Card>
          )}

          {/* 操作提示 */}
          <Card className="p-4 bg-blue-50 border-blue-200">
            <h4 className="mb-2 text-blue-900 text-sm">💡 使用提示</h4>
            <ul className="space-y-1 text-xs text-blue-800">
              <li>• 拖动进度条可快速定位</li>
              <li>• 点击速度按钮可切换播放速度</li>
              <li>• 绿色轨迹为已走路径</li>
              <li>• 蓝色轨迹为完整路径</li>
            </ul>
          </Card>
        </div>
      </div>
    </div>
  );
}
