import { useState, useEffect, useRef } from 'react';
import { Card } from '../../ui/card';
import { Badge } from '../../ui/badge';
import { Button } from '../../ui/button';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '../../ui/dialog';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../../ui/table';
import { MapPin, TrendingUp, CheckCircle, Map } from 'lucide-react';

// GPS轨迹点类型
interface GPSPoint {
  lat: number;
  lng: number;
  timestamp: string;
  speed: number;
  workingStatus: boolean;
}

// 作业记录类型
interface OperationRecord {
  id: string;
  machineryName: string;
  fieldName: string;
  operationType: string;
  plannedArea: number;
  actualArea: number;
  coverage: number;
  quality: string;
  startTime: string;
  endTime: string;
  duration: number;
  trajectory?: GPSPoint[];
  fieldCenter?: { lat: number; lng: number };
}

export function OperationRecord() {
  const [records, setRecords] = useState<OperationRecord[]>([]);
  const [showTrajectoryDialog, setShowTrajectoryDialog] = useState(false);
  const [selectedRecord, setSelectedRecord] = useState<OperationRecord | null>(null);
  const mapRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    // 模拟作业记录数据
    const mockRecords: OperationRecord[] = [
      {
        id: 'record-1',
        machineryName: '约翰迪尔拖拉机',
        fieldName: '1号地块',
        operationType: '耕地',
        plannedArea: 50,
        actualArea: 48.5,
        coverage: 97,
        quality: '优秀',
        startTime: '2024-10-12T08:00:00',
        endTime: '2024-10-12T15:30:00',
        duration: 7.5,
        fieldCenter: { lat: 30.2741, lng: 120.1551 },
        trajectory: generateMockTrajectory({ lat: 30.2741, lng: 120.1551 }),
      },
      {
        id: 'record-2',
        machineryName: '久保田收割机',
        fieldName: '2号地块',
        operationType: '收获',
        plannedArea: 80,
        actualArea: 79.2,
        coverage: 99,
        quality: '良好',
        startTime: '2024-10-11T07:00:00',
        endTime: '2024-10-11T18:00:00',
        duration: 11,
        fieldCenter: { lat: 30.2850, lng: 120.1700 },
        trajectory: generateMockTrajectory({ lat: 30.2850, lng: 120.1700 }),
      },
    ];
    setRecords(mockRecords);
  }, []);

  // 生成模拟轨迹数据
  const generateMockTrajectory = (center: { lat: number; lng: number }): GPSPoint[] => {
    const points: GPSPoint[] = [];
    const startTime = new Date('2024-10-12T08:00:00').getTime();
    const fieldSize = { width: 0.008, height: 0.006 }; // 地块大小（度）
    
    // 生成往返式作业轨迹
    const rows = 15;
    const spacing = fieldSize.height / rows;
    
    for (let i = 0; i < rows; i++) {
      const lat = center.lat - fieldSize.height / 2 + i * spacing;
      const direction = i % 2 === 0 ? 1 : -1;
      const steps = 25;
      
      for (let j = 0; j < steps; j++) {
        const progress = j / steps;
        const lng = direction > 0
          ? center.lng - fieldSize.width / 2 + progress * fieldSize.width
          : center.lng + fieldSize.width / 2 - progress * fieldSize.width;
        
        points.push({
          lat,
          lng,
          timestamp: new Date(startTime + points.length * 60000).toISOString(),
          speed: 5 + Math.random() * 2,
          workingStatus: true,
        });
      }
      
      // 添加转弯点
      if (i < rows - 1) {
        const turnLat = center.lat - fieldSize.height / 2 + (i + 0.5) * spacing;
        const turnLng = direction > 0
          ? center.lng + fieldSize.width / 2
          : center.lng - fieldSize.width / 2;
        
        points.push({
          lat: turnLat,
          lng: turnLng,
          timestamp: new Date(startTime + points.length * 60000).toISOString(),
          speed: 2,
          workingStatus: false,
        });
      }
    }
    
    return points;
  };

  // 查看轨迹
  const handleViewTrajectory = (record: OperationRecord) => {
    setSelectedRecord(record);
    setShowTrajectoryDialog(true);
  };

  // 绘制地图轨迹
  useEffect(() => {
    if (!showTrajectoryDialog || !selectedRecord || !mapRef.current) return;
    if (!(window as any).AMap) return;

    const map = new (window as any).AMap.Map(mapRef.current, {
      center: [selectedRecord.fieldCenter?.lng || 120.1551, selectedRecord.fieldCenter?.lat || 30.2741],
      zoom: 15,
      mapStyle: 'amap://styles/normal',
    });

    if (selectedRecord.trajectory && selectedRecord.trajectory.length > 0) {
      // 分离作业中和非作业的点
      const workingPath: any[] = [];
      const idlePath: any[] = [];

      selectedRecord.trajectory.forEach(point => {
        const lnglat = [point.lng, point.lat];
        if (point.workingStatus) {
          workingPath.push(lnglat);
        } else {
          idlePath.push(lnglat);
        }
      });

      // 绘制作业路径（绿色）
      if (workingPath.length > 1) {
        const workingPolyline = new (window as any).AMap.Polyline({
          path: workingPath,
          strokeColor: '#10b981',
          strokeWeight: 4,
          strokeOpacity: 0.8,
        });
        map.add(workingPolyline);
      }

      // 绘制空转路径（灰色）
      if (idlePath.length > 1) {
        const idlePolyline = new (window as any).AMap.Polyline({
          path: idlePath,
          strokeColor: '#9ca3af',
          strokeWeight: 2,
          strokeOpacity: 0.5,
          strokeStyle: 'dashed',
        });
        map.add(idlePolyline);
      }

      // 添加起点标记
      const startMarker = new (window as any).AMap.Marker({
        position: [selectedRecord.trajectory[0].lng, selectedRecord.trajectory[0].lat],
        icon: new (window as any).AMap.Icon({
          image: 'https://webapi.amap.com/theme/v1.3/markers/n/start.png',
          size: new (window as any).AMap.Size(25, 34),
          imageSize: new (window as any).AMap.Size(25, 34),
        }),
        title: '起点',
      });
      map.add(startMarker);

      // 添加终点标记
      const endPoint = selectedRecord.trajectory[selectedRecord.trajectory.length - 1];
      const endMarker = new (window as any).AMap.Marker({
        position: [endPoint.lng, endPoint.lat],
        icon: new (window as any).AMap.Icon({
          image: 'https://webapi.amap.com/theme/v1.3/markers/n/end.png',
          size: new (window as any).AMap.Size(25, 34),
          imageSize: new (window as any).AMap.Size(25, 34),
        }),
        title: '终点',
      });
      map.add(endMarker);

      // 自动调整视野
      map.setFitView();
    }

    return () => {
      map.destroy();
    };
  }, [showTrajectoryDialog, selectedRecord]);

  const getQualityColor = (quality: string) => {
    switch (quality) {
      case '优秀': return 'bg-success-muted text-success';
      case '良好': return 'bg-info-muted text-info';
      case '一般': return 'bg-warning-muted text-warning';
      default: return 'bg-muted text-muted-foreground';
    }
  };

  return (
    <div className="space-y-6">
      <div>
        <h2 className="text-primary">作业数据记录</h2>
        <p className="text-muted-foreground">自动记录作业面积、轨迹和质量评估</p>
      </div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">总作业次数</div>
          <div className="mt-1">{records.length}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">总作业面积</div>
          <div className="mt-1 text-success">
            {records.reduce((sum, r) => sum + r.actualArea, 0).toFixed(1)} 亩
          </div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">平均覆盖率</div>
          <div className="mt-1">
            {(records.reduce((sum, r) => sum + r.coverage, 0) / records.length || 0).toFixed(0)}%
          </div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">优质作业</div>
          <div className="mt-1 text-info">
            {records.filter(r => r.quality === '优秀').length}
          </div>
        </Card>
      </div>

      {/* 作业记录列表 */}
      <Card>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>农机</TableHead>
              <TableHead>地块</TableHead>
              <TableHead>作业类型</TableHead>
              <TableHead>计划面积</TableHead>
              <TableHead>实际面积</TableHead>
              <TableHead>覆盖率</TableHead>
              <TableHead>作业时长</TableHead>
              <TableHead>质量评估</TableHead>
              <TableHead>操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {records.map(record => (
              <TableRow key={record.id}>
                <TableCell>{record.machineryName}</TableCell>
                <TableCell>{record.fieldName}</TableCell>
                <TableCell>{record.operationType}</TableCell>
                <TableCell>{record.plannedArea} 亩</TableCell>
                <TableCell>{record.actualArea} 亩</TableCell>
                <TableCell>
                  <div className="flex items-center gap-2">
                    <div className="flex-1 bg-gray-200 rounded-full h-2">
                      <div
                        className="bg-success h-2 rounded-full"
                        style={{ width: `${record.coverage}%` }}
                      />
                    </div>
                    <span className="text-sm">{record.coverage}%</span>
                  </div>
                </TableCell>
                <TableCell>{record.duration} 小时</TableCell>
                <TableCell>
                  <Badge variant="secondary" className={getQualityColor(record.quality)}>
                    {record.quality}
                  </Badge>
                </TableCell>
                <TableCell>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => handleViewTrajectory(record)}
                    className="gap-1"
                  >
                    <Map className="w-4 h-4" />
                    查看轨迹
                  </Button>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </Card>

      {/* 功能说明 */}
      <Card className="p-6 bg-info-muted border-info">
        <h4 className="mb-3 text-muted-foreground">功能特性</h4>
        <ul className="space-y-2 text-sm text-muted-foreground">
          <li>• 基于GPS轨迹自动计算实际作业面积</li>
          <li>• 绘制作业轨迹图，可视化作业路径</li>
          <li>• 根据传感器数据评估作业质量（播种均匀度、深浅一致性）</li>
          <li>• 所有数据自动归档，形成完整作业档案</li>
          <li>• 点击"查看轨迹"按钮可回看每条记录的详细作业路径</li>
        </ul>
      </Card>

      {/* 轨迹查看对话框 */}
      <Dialog open={showTrajectoryDialog} onOpenChange={setShowTrajectoryDialog}>
        <DialogContent className="max-w-5xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>作业轨迹回看</DialogTitle>
            <DialogDescription>
              {selectedRecord && (
                <>
                  {selectedRecord.machineryName} - {selectedRecord.fieldName} - {selectedRecord.operationType}
                </>
              )}
            </DialogDescription>
          </DialogHeader>

          {selectedRecord && (
            <div className="space-y-4">
              {/* 作业信息 */}
              <Card className="p-4">
                <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
                  <div>
                    <div className="text-muted-foreground">开始时间</div>
                    <div className="mt-1">
                      {new Date(selectedRecord.startTime).toLocaleString('zh-CN', {
                        month: '2-digit',
                        day: '2-digit',
                        hour: '2-digit',
                        minute: '2-digit'
                      })}
                    </div>
                  </div>
                  <div>
                    <div className="text-muted-foreground">结束时间</div>
                    <div className="mt-1">
                      {new Date(selectedRecord.endTime).toLocaleString('zh-CN', {
                        month: '2-digit',
                        day: '2-digit',
                        hour: '2-digit',
                        minute: '2-digit'
                      })}
                    </div>
                  </div>
                  <div>
                    <div className="text-muted-foreground">作业时长</div>
                    <div className="mt-1">{selectedRecord.duration} 小时</div>
                  </div>
                  <div>
                    <div className="text-muted-foreground">质量评估</div>
                    <div className="mt-1">
                      <Badge variant="secondary" className={getQualityColor(selectedRecord.quality)}>
                        {selectedRecord.quality}
                      </Badge>
                    </div>
                  </div>
                </div>
              </Card>

              {/* 面积统计 */}
              <Card className="p-4">
                <h4 className="text-sm mb-3">面积统计</h4>
                <div className="grid grid-cols-3 gap-4 text-sm">
                  <div>
                    <div className="text-muted-foreground">计划面积</div>
                    <div className="mt-1 text-info">{selectedRecord.plannedArea} 亩</div>
                  </div>
                  <div>
                    <div className="text-muted-foreground">实际面积</div>
                    <div className="mt-1 text-success">{selectedRecord.actualArea} 亩</div>
                  </div>
                  <div>
                    <div className="text-muted-foreground">覆盖率</div>
                    <div className="mt-1">
                      <div className="flex items-center gap-2">
                        <div className="flex-1 bg-gray-200 rounded-full h-2">
                          <div
                            className="bg-success h-2 rounded-full"
                            style={{ width: `${selectedRecord.coverage}%` }}
                          />
                        </div>
                        <span>{selectedRecord.coverage}%</span>
                      </div>
                    </div>
                  </div>
                </div>
              </Card>

              {/* 图例 */}
              <div className="flex items-center gap-4 text-sm">
                <div className="flex items-center gap-2">
                  <div className="w-4 h-1 bg-success rounded" />
                  <span>作业路径</span>
                </div>
                <div className="flex items-center gap-2">
                  <div className="w-4 h-1 bg-gray-400 rounded border-dashed" />
                  <span>空转路径</span>
                </div>
                <div className="flex items-center gap-2">
                  <MapPin className="w-4 h-4 text-success" />
                  <span>起点</span>
                </div>
                <div className="flex items-center gap-2">
                  <MapPin className="w-4 h-4 text-error" />
                  <span>终点</span>
                </div>
              </div>

              {/* 地图区域 */}
              <div
                ref={mapRef}
                className="w-full h-[500px] rounded-lg border"
              />

              {/* 轨迹统计 */}
              <div className="grid grid-cols-3 gap-3">
                <Card className="p-3">
                  <div className="text-xs text-muted-foreground">轨迹点数</div>
                  <div className="mt-1 text-sm">
                    {selectedRecord.trajectory?.length || 0}
                  </div>
                </Card>
                <Card className="p-3">
                  <div className="text-xs text-muted-foreground">作业点数</div>
                  <div className="mt-1 text-sm text-success">
                    {selectedRecord.trajectory?.filter(p => p.workingStatus).length || 0}
                  </div>
                </Card>
                <Card className="p-3">
                  <div className="text-xs text-muted-foreground">空转点数</div>
                  <div className="mt-1 text-sm text-gray-600">
                    {selectedRecord.trajectory?.filter(p => !p.workingStatus).length || 0}
                  </div>
                </Card>
              </div>

              {/* 操作按钮 */}
              <div className="flex justify-end">
                <Button variant="outline" onClick={() => setShowTrajectoryDialog(false)}>
                  关闭
                </Button>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}
