import { useState, useRef, useEffect } from 'react';
import { Card } from '../../ui/card';
import { Button } from '../../ui/button';
import { Input } from '../../ui/input';
import { Label } from '../../ui/label';
import { Badge } from '../../ui/badge';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from '../../ui/dialog';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../../ui/select';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../../ui/tabs';
import { 
  Map, Grid3x3, Download, Upload, Edit3, Trash2, Save, 
  Play, Plus, Eye, EyeOff, AlertTriangle, CheckCircle,
  Navigation, Maximize2, ZoomIn, ZoomOut, Move, Square, MapPin
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';
import { Field } from '../../../types/field';

// 路线数据类型
interface RoutePoint {
  lng: number;
  lat: number;
}

interface Obstacle {
  id: string;
  name: string;
  points: RoutePoint[];
  type: 'tree' | 'building' | 'pond' | 'other';
}

interface RoutePlan {
  id: string;
  name: string;
  fieldId?: string;              // 关联地块ID
  fieldName?: string;            // 关联地块名称
  fieldBoundary: RoutePoint[];
  obstacles: Obstacle[];
  workingLines: RoutePoint[][];
  params: RouteParams;
  stats: RouteStats;
  createdAt: string;
  status: 'draft' | 'approved' | 'exported';
}

interface RouteParams {
  rowSpacing: number;        // 作业行距(米)
  workingDirection: number;  // 耕作方向(度)
  overlapWidth: number;      // 重叠宽度(米)
  workingWidth: number;      // 作业幅宽(米)
  turnRadius: number;        // 转弯半径(米)
  entryPoint: 'auto' | 'manual';  // 入口点
  pathPattern: 'parallel' | 'spiral' | 'zigzag';  // 路径模式
}

interface RouteStats {
  totalRows: number;         // 总行数
  totalDistance: number;     // 总里程(km)
  workingArea: number;       // 作业面积(亩)
  estimatedTime: number;     // 预计用时(小时)
  fuelEstimate: number;      // 预计油耗(升)
  efficiency: number;        // 覆盖效率(%)
}

export function RoutePlanning() {
  const [routes, setRoutes] = useState<RoutePlan[]>([]);
  const [selectedRoute, setSelectedRoute] = useState<RoutePlan | null>(null);
  const [drawMode, setDrawMode] = useState<'none' | 'boundary' | 'obstacle'>('none');
  const [currentDrawing, setCurrentDrawing] = useState<RoutePoint[]>([]);
  const [showRouteDialog, setShowRouteDialog] = useState(false);
  const [showExportDialog, setShowExportDialog] = useState(false);
  const [showSaveDialog, setShowSaveDialog] = useState(false);
  const [showFieldSelectDialog, setShowFieldSelectDialog] = useState(false);
  const [editingRoute, setEditingRoute] = useState<RoutePlan | null>(null);
  const [editingName, setEditingName] = useState<string>('');
  const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
  const [fields, setFields] = useState<Field[]>([]);
  const [selectedFieldId, setSelectedFieldId] = useState<string>('none');
  const [visibleLayers, setVisibleLayers] = useState({
    boundary: true,
    obstacles: true,
    routes: true,
    grid: true,
  });

  const canvasRef = useRef<HTMLCanvasElement>(null);
  const [canvasSize, setCanvasSize] = useState({ width: 800, height: 600 });
  const [zoom, setZoom] = useState(1);
  const [offset, setOffset] = useState({ x: 0, y: 0 });

  const [routeParams, setRouteParams] = useState<RouteParams>({
    rowSpacing: 3,
    workingDirection: 0,
    overlapWidth: 0.3,
    workingWidth: 2.5,
    turnRadius: 5,
    entryPoint: 'auto',
    pathPattern: 'parallel',
  });

  useEffect(() => {
    // 加载地块数据
    const fieldsData = localStorage.getItem('smart_agriculture_fields');
    if (fieldsData) {
      setFields(JSON.parse(fieldsData));
    }

    // 加载已有路线
    const savedRoutes = localStorage.getItem('smart_agriculture_route_plans');
    if (savedRoutes) {
      setRoutes(JSON.parse(savedRoutes));
    } else {
      // 创建示例路线
      const mockRoute: RoutePlan = {
        id: 'route-1',
        name: '东地1号作业路线',
        fieldBoundary: [
          { lng: 100, lat: 100 },
          { lng: 500, lat: 100 },
          { lng: 500, lat: 400 },
          { lng: 100, lat: 400 },
        ],
        obstacles: [
          {
            id: 'obs-1',
            name: '水塘',
            type: 'pond',
            points: [
              { lng: 250, lat: 200 },
              { lng: 300, lat: 200 },
              { lng: 300, lat: 250 },
              { lng: 250, lat: 250 },
            ],
          },
        ],
        workingLines: [],
        params: routeParams,
        stats: {
          totalRows: 0,
          totalDistance: 0,
          workingArea: 0,
          estimatedTime: 0,
          fuelEstimate: 0,
          efficiency: 0,
        },
        createdAt: new Date().toISOString(),
        status: 'draft',
      };
      setRoutes([mockRoute]);
      setSelectedRoute(mockRoute);
    }
  }, []);

  useEffect(() => {
    // 保存路线
    if (routes.length > 0) {
      localStorage.setItem('smart_agriculture_route_plans', JSON.stringify(routes));
    }
  }, [routes]);

  useEffect(() => {
    // 绘制地图
    drawMap();
  }, [selectedRoute, currentDrawing, drawMode, visibleLayers, zoom, offset]);

  // 创建新路线 - 直接创建，在地图区域选择地块
  const createNewRoute = () => {
    if (hasUnsavedChanges) {
      toast.error('当前路线有未保存的更改，请先保存');
      return;
    }

    // 直接创建空路线，不弹窗
    const newRoute: RoutePlan = {
      id: `route-${Date.now()}`,
      name: `路线规划${routes.length + 1}`,
      fieldId: undefined,
      fieldName: undefined,
      fieldBoundary: [],
      obstacles: [],
      workingLines: [],
      params: routeParams,
      stats: {
        totalRows: 0,
        totalDistance: 0,
        workingArea: 0,
        estimatedTime: 0,
        fuelEstimate: 0,
        efficiency: 0,
      },
      createdAt: new Date().toISOString(),
      status: 'draft',
    };

    setRoutes([...routes, newRoute]);
    setSelectedRoute(newRoute);
    toast.success('新建路线规划成功，请在地图区域选择关联地块');
  };

  const drawMap = () => {
    const canvas = canvasRef.current;
    if (!canvas) return;

    const ctx = canvas.getContext('2d');
    if (!ctx) return;

    // 清空画布
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // 应用变换
    ctx.save();
    ctx.translate(offset.x, offset.y);
    ctx.scale(zoom, zoom);

    // 绘制网格
    if (visibleLayers.grid) {
      drawGrid(ctx);
    }

    if (selectedRoute) {
      // 绘制农田边界
      if (visibleLayers.boundary && selectedRoute.fieldBoundary.length > 0) {
        drawPolygon(ctx, selectedRoute.fieldBoundary, '#10b981', 3, false);
      }

      // 绘制障碍物
      if (visibleLayers.obstacles) {
        selectedRoute.obstacles.forEach(obstacle => {
          const color = getObstacleColor(obstacle.type);
          drawPolygon(ctx, obstacle.points, color, 2, true);
        });
      }

      // 绘制作业路线
      if (visibleLayers.routes && selectedRoute.workingLines.length > 0) {
        selectedRoute.workingLines.forEach((line, index) => {
          drawPath(ctx, line, '#3b82f6', 2);
          // 绘制行号
          if (line.length > 0) {
            ctx.fillStyle = '#3b82f6';
            ctx.font = '12px sans-serif';
            ctx.fillText(`${index + 1}`, line[0].lng, line[0].lat - 5);
          }
        });
      }
    }

    // 绘制当前绘制中的形状
    if (currentDrawing.length > 0) {
      drawPolygon(ctx, currentDrawing, '#f59e0b', 2, false);
    }

    ctx.restore();
  };

  const drawGrid = (ctx: CanvasRenderingContext2D) => {
    const gridSize = 50;
    ctx.strokeStyle = '#e5e7eb';
    ctx.lineWidth = 0.5;

    for (let x = 0; x < canvasSize.width; x += gridSize) {
      ctx.beginPath();
      ctx.moveTo(x, 0);
      ctx.lineTo(x, canvasSize.height);
      ctx.stroke();
    }

    for (let y = 0; y < canvasSize.height; y += gridSize) {
      ctx.beginPath();
      ctx.moveTo(0, y);
      ctx.lineTo(canvasSize.width, y);
      ctx.stroke();
    }
  };

  const drawPolygon = (
    ctx: CanvasRenderingContext2D, 
    points: RoutePoint[], 
    color: string, 
    lineWidth: number,
    fill: boolean
  ) => {
    if (points.length < 2) return;

    ctx.beginPath();
    ctx.moveTo(points[0].lng, points[0].lat);
    
    for (let i = 1; i < points.length; i++) {
      ctx.lineTo(points[i].lng, points[i].lat);
    }
    
    ctx.closePath();
    ctx.strokeStyle = color;
    ctx.lineWidth = lineWidth;
    ctx.stroke();

    if (fill) {
      ctx.fillStyle = color + '30'; // 30% opacity
      ctx.fill();
    }

    // 绘制顶点
    points.forEach(point => {
      ctx.beginPath();
      ctx.arc(point.lng, point.lat, 4, 0, Math.PI * 2);
      ctx.fillStyle = color;
      ctx.fill();
    });
  };

  const drawPath = (ctx: CanvasRenderingContext2D, points: RoutePoint[], color: string, lineWidth: number) => {
    if (points.length < 2) return;

    ctx.beginPath();
    ctx.moveTo(points[0].lng, points[0].lat);
    
    for (let i = 1; i < points.length; i++) {
      ctx.lineTo(points[i].lng, points[i].lat);
    }
    
    ctx.strokeStyle = color;
    ctx.lineWidth = lineWidth;
    ctx.stroke();

    // 绘制箭头表示方向
    if (points.length > 1) {
      const last = points[points.length - 1];
      const beforeLast = points[points.length - 2];
      drawArrow(ctx, beforeLast, last, color);
    }
  };

  const drawArrow = (ctx: CanvasRenderingContext2D, from: RoutePoint, to: RoutePoint, color: string) => {
    const angle = Math.atan2(to.lat - from.lat, to.lng - from.lng);
    const arrowLength = 10;
    
    ctx.save();
    ctx.translate(to.lng, to.lat);
    ctx.rotate(angle);
    
    ctx.beginPath();
    ctx.moveTo(0, 0);
    ctx.lineTo(-arrowLength, -arrowLength / 2);
    ctx.lineTo(-arrowLength, arrowLength / 2);
    ctx.closePath();
    
    ctx.fillStyle = color;
    ctx.fill();
    
    ctx.restore();
  };

  const getObstacleColor = (type: string): string => {
    switch (type) {
      case 'tree': return '#22c55e';
      case 'building': return '#ef4444';
      case 'pond': return '#3b82f6';
      default: return '#f59e0b';
    }
  };

  const handleCanvasClick = (e: React.MouseEvent<HTMLCanvasElement>) => {
    if (drawMode === 'none') return;

    const canvas = canvasRef.current;
    if (!canvas) return;

    const rect = canvas.getBoundingClientRect();
    const x = (e.clientX - rect.left - offset.x) / zoom;
    const y = (e.clientY - rect.top - offset.y) / zoom;

    setCurrentDrawing([...currentDrawing, { lng: x, lat: y }]);
  };

  const finishDrawing = () => {
    if (currentDrawing.length < 3) {
      toast.error('至少需要3个点才能完成绘制');
      return;
    }

    if (!selectedRoute) {
      toast.error('请先选择或创建一个路线规划');
      return;
    }

    if (drawMode === 'boundary') {
      setSelectedRoute({
        ...selectedRoute,
        fieldBoundary: currentDrawing,
      });
      setHasUnsavedChanges(true);
      toast.success('农田边界绘制完成，请点击保存按钮保存');
    } else if (drawMode === 'obstacle') {
      const newObstacle: Obstacle = {
        id: `obs-${Date.now()}`,
        name: `障碍物${selectedRoute.obstacles.length + 1}`,
        type: 'other',
        points: currentDrawing,
      };
      setSelectedRoute({
        ...selectedRoute,
        obstacles: [...selectedRoute.obstacles, newObstacle],
      });
      setHasUnsavedChanges(true);
      toast.success('障碍物标注完成，请点击保存按钮保存');
    }

    setCurrentDrawing([]);
    setDrawMode('none');
  };

  const cancelDrawing = () => {
    setCurrentDrawing([]);
    setDrawMode('none');
  };

  const generateRoute = () => {
    if (!selectedRoute) {
      toast.error('请先选择或创建一个路线规划');
      return;
    }

    // 校验地块必选
    if (!selectedRoute.fieldId || !selectedRoute.fieldName) {
      toast.error('请先选择关联地块，作业路线规划必须关联地块');
      return;
    }

    if (selectedRoute.fieldBoundary.length < 3) {
      toast.error('地块边界点数不足，无法生成作业路线');
      return;
    }

    // 使用简化的平行线覆盖算法
    const workingLines: RoutePoint[][] = [];
    const boundary = selectedRoute.fieldBoundary;
    
    // 计算边界范围
    const minX = Math.min(...boundary.map(p => p.lng));
    const maxX = Math.max(...boundary.map(p => p.lng));
    const minY = Math.min(...boundary.map(p => p.lat));
    const maxY = Math.max(...boundary.map(p => p.lat));

    // 根据耕作方向调整
    const angle = (routeParams.workingDirection * Math.PI) / 180;
    const spacing = routeParams.rowSpacing * 10; // 转换为像素单位

    // 生成平行作业线
    let currentY = minY + spacing;
    let lineIndex = 0;

    while (currentY < maxY) {
      const line: RoutePoint[] = [];
      
      if (lineIndex % 2 === 0) {
        // 从左到右
        line.push({ lng: minX, lat: currentY });
        line.push({ lng: maxX, lat: currentY });
      } else {
        // 从右到左（往返模式）
        line.push({ lng: maxX, lat: currentY });
        line.push({ lng: minX, lat: currentY });
      }

      workingLines.push(line);
      currentY += spacing;
      lineIndex++;
    }

    // 计算统计数据
    const totalDistance = workingLines.reduce((sum, line) => {
      let dist = 0;
      for (let i = 1; i < line.length; i++) {
        const dx = line[i].lng - line[i-1].lng;
        const dy = line[i].lat - line[i-1].lat;
        dist += Math.sqrt(dx * dx + dy * dy);
      }
      return sum + dist;
    }, 0) / 1000; // 转换为km

    const workingArea = ((maxX - minX) * (maxY - minY)) / 10000 * 0.15; // 转换为亩
    const estimatedTime = totalDistance / 5; // 假设平均速度5km/h
    const fuelEstimate = totalDistance * 3; // 假设每公里3升
    const efficiency = 95; // 覆盖效率

    const stats: RouteStats = {
      totalRows: workingLines.length,
      totalDistance: parseFloat(totalDistance.toFixed(2)),
      workingArea: parseFloat(workingArea.toFixed(2)),
      estimatedTime: parseFloat(estimatedTime.toFixed(2)),
      fuelEstimate: parseFloat(fuelEstimate.toFixed(2)),
      efficiency,
    };

    setSelectedRoute({
      ...selectedRoute,
      workingLines,
      params: routeParams,
      stats,
    });

    setHasUnsavedChanges(true);

    toast.success(`路线生成成功！共${workingLines.length}行，总里程${totalDistance.toFixed(2)}km，请点击保存按钮保存路线`);
  };

  const saveRoute = () => {
    if (!selectedRoute) {
      toast.error('没有要保存的路线');
      return;
    }

    // 校验地块必选
    if (!selectedRoute.fieldId || !selectedRoute.fieldName) {
      toast.error('请先选择关联地块，作业路线规划必须关联地块');
      return;
    }

    const updatedRoutes = routes.map(r => 
      r.id === selectedRoute.id ? selectedRoute : r
    );
    
    setRoutes(updatedRoutes);
    setHasUnsavedChanges(false);
    toast.success('路线已保存');
  };

  const deleteRoute = (id: string) => {
    if (hasUnsavedChanges && selectedRoute?.id === id) {
      toast.error('当前路线有未保存的更改，请先保存或放弃更改');
      return;
    }

    setRoutes(routes.filter(r => r.id !== id));
    if (selectedRoute?.id === id) {
      setSelectedRoute(routes[0] || null);
      setHasUnsavedChanges(false);
    }
    toast.success('路线已删除');
  };

  const startEditName = (route: RoutePlan) => {
    setEditingRoute(route);
    setEditingName(route.name);
    setShowSaveDialog(true);
  };

  const saveRouteName = () => {
    if (!editingRoute) return;
    
    if (!editingName.trim()) {
      toast.error('路线名称不能为空');
      return;
    }

    const updatedRoutes = routes.map(r => 
      r.id === editingRoute.id ? { ...r, name: editingName } : r
    );
    
    setRoutes(updatedRoutes);
    
    if (selectedRoute?.id === editingRoute.id) {
      setSelectedRoute({ ...selectedRoute, name: editingName });
    }

    setShowSaveDialog(false);
    setEditingRoute(null);
    setEditingName('');
    toast.success('路线名称已更新');
  };

  const exportRoute = (format: 'json' | 'kml' | 'shp') => {
    if (!selectedRoute) {
      toast.error('请先选择要导出的路线');
      return;
    }

    let content = '';
    let filename = '';
    let mimeType = '';

    switch (format) {
      case 'json':
        content = JSON.stringify(selectedRoute, null, 2);
        filename = `${selectedRoute.name}.json`;
        mimeType = 'application/json';
        break;
      case 'kml':
        content = generateKML(selectedRoute);
        filename = `${selectedRoute.name}.kml`;
        mimeType = 'application/vnd.google-earth.kml+xml';
        break;
      case 'shp':
        toast.info('SHP格式导出需要后端支持');
        return;
    }

    const blob = new Blob([content], { type: mimeType });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    a.click();
    URL.revokeObjectURL(url);

    toast.success(`路线已导出为${format.toUpperCase()}格式`);
    setShowExportDialog(false);
  };

  const generateKML = (route: RoutePlan): string => {
    const kml = `<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
  <Document>
    <name>${route.name}</name>
    <description>作业路线规划</description>
    
    <!-- 农田边界 -->
    <Placemark>
      <name>农田边界</name>
      <Polygon>
        <outerBoundaryIs>
          <LinearRing>
            <coordinates>
              ${route.fieldBoundary.map(p => `${p.lng},${p.lat},0`).join(' ')}
            </coordinates>
          </LinearRing>
        </outerBoundaryIs>
      </Polygon>
    </Placemark>
    
    <!-- 作业路线 -->
    ${route.workingLines.map((line, index) => `
    <Placemark>
      <name>作业线${index + 1}</name>
      <LineString>
        <coordinates>
          ${line.map(p => `${p.lng},${p.lat},0`).join(' ')}
        </coordinates>
      </LineString>
    </Placemark>
    `).join('')}
  </Document>
</kml>`;
    return kml;
  };

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'draft':
        return <Badge variant="outline" className="bg-gray-100">草稿</Badge>;
      case 'approved':
        return <Badge variant="outline" className="bg-success-muted text-success">已审核</Badge>;
      case 'exported':
        return <Badge variant="outline" className="bg-info-muted text-info">已导出</Badge>;
      default:
        return <Badge variant="outline">未知</Badge>;
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-primary">作业路线规划</h2>
          <p className="text-muted-foreground">基于地块信息智能规划全覆盖无重复的作业路线</p>
        </div>
        <div className="flex gap-2">
          {hasUnsavedChanges && (
            <Button variant="outline" onClick={saveRoute} className="bg-warning-muted border-warning">
              <Save className="w-4 h-4 mr-2" />
              保存更改
            </Button>
          )}
          <Button onClick={createNewRoute}>
            <Plus className="w-4 h-4 mr-2" />
            新建规划
          </Button>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-4 gap-6">
        {/* 路线列表 */}
        <Card className="p-4">
          <h3 className="mb-4">路线列表</h3>
          <div className="space-y-2">
            {routes.map(route => (
              <div
                key={route.id}
                className={`p-3 rounded-lg border transition-colors ${
                  selectedRoute?.id === route.id
                    ? 'bg-success-muted border-success'
                    : 'hover:bg-gray-50'
                }`}
              >
                <div className="flex items-start justify-between">
                  <div 
                    className="flex-1 cursor-pointer"
                    onClick={() => {
                      if (hasUnsavedChanges && selectedRoute?.id !== route.id) {
                        toast.error('当前路线有未保存的更改，请先保存');
                        return;
                      }
                      setSelectedRoute(route);
                    }}
                  >
                    <div className="flex items-center gap-2 mb-1">
                      <span className="text-sm">{route.name}</span>
                      {getStatusBadge(route.status)}
                      {selectedRoute?.id === route.id && hasUnsavedChanges && (
                        <Badge variant="outline" className="bg-warning-muted text-warning">
                          未保存
                        </Badge>
                      )}
                    </div>
                    <div className="text-xs text-muted-foreground">
                      {route.stats.totalRows}行 · {route.stats.totalDistance}km
                    </div>
                  </div>
                  <div className="flex gap-1">
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={(e) => {
                        e.stopPropagation();
                        startEditName(route);
                      }}
                      title="编辑名称"
                    >
                      <Edit3 className="w-3 h-3" />
                    </Button>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={(e) => {
                        e.stopPropagation();
                        deleteRoute(route.id);
                      }}
                      title="删除路线"
                    >
                      <Trash2 className="w-3 h-3" />
                    </Button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </Card>

        {/* 地图区域 */}
        <div className="lg:col-span-2 space-y-4">
          {/* 地块信息卡片 */}
          {selectedRoute && (
            <Card className="p-4 bg-gradient-to-r from-blue-50 to-green-50 border-blue-200">
              <div>
                <h4 className="mb-3 text-muted-foreground flex items-center gap-2">
                  <MapPin className="w-4 h-4" />
                  关联地块
                </h4>
                {selectedRoute.fieldName ? (
                  <div className="space-y-3">
                    <div className="flex items-center gap-2">
                      <Badge variant="outline" className="bg-white text-success border-success">
                        ✓ 当前: {selectedRoute.fieldName}
                      </Badge>
                      <span className="text-sm text-success">
                        地块边界已加载
                      </span>
                    </div>
                    <Select 
                      value={selectedRoute.fieldId || 'none'} 
                      onValueChange={(value) => {
                        if (value && value !== 'none') {
                          const field = fields.find(f => f.id === value);
                          if (field) {
                            const fieldBoundary = field.coordinates.map(coord => ({
                              lng: coord.lng * 10 + 100,
                              lat: coord.lat * 10 + 100,
                            }));
                            const updatedRoute = {
                              ...selectedRoute,
                              fieldId: value,
                              fieldName: field.name,
                              fieldBoundary,
                              name: `${field.name}作业路线`,
                            };
                            const updatedRoutes = routes.map(r => 
                              r.id === selectedRoute.id ? updatedRoute : r
                            );
                            setRoutes(updatedRoutes);
                            setSelectedRoute(updatedRoute);
                            setHasUnsavedChanges(true);
                            toast.success(`已更换地块：${field.name}，边界已重新加载`);
                          }
                        }
                      }}
                    >
                      <SelectTrigger className="bg-white">
                        <SelectValue placeholder="更换地块" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="none" disabled>
                          当前: {selectedRoute.fieldName}
                        </SelectItem>
                        {fields.filter(f => f.status === 'active' && f.id !== selectedRoute.fieldId).map(field => (
                          <SelectItem key={field.id} value={field.id}>
                            <div className="flex items-center gap-2">
                              <MapPin className="w-3 h-3" />
                              {field.name} ({field.area}亩 · {field.location})
                            </div>
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                ) : (
                  <div className="space-y-3">
                    <div className="p-3 bg-warning-muted border border-warning rounded-lg">
                      <p className="text-sm text-warning">
                        ⚠️ 该路线未关联地块，请选择地块
                      </p>
                      <p className="text-xs text-warning mt-1">
                        作业路线规划必须关联地块信息
                      </p>
                    </div>
                    <Select 
                      value="none" 
                      onValueChange={(value) => {
                        if (value !== 'none') {
                          const field = fields.find(f => f.id === value);
                          if (field) {
                            const fieldBoundary = field.coordinates.map(coord => ({
                              lng: coord.lng * 10 + 100,
                              lat: coord.lat * 10 + 100,
                            }));
                            const updatedRoute = {
                              ...selectedRoute,
                              fieldId: value,
                              fieldName: field.name,
                              fieldBoundary,
                              name: `${field.name}作业路线`,
                            };
                            const updatedRoutes = routes.map(r => 
                              r.id === selectedRoute.id ? updatedRoute : r
                            );
                            setRoutes(updatedRoutes);
                            setSelectedRoute(updatedRoute);
                            setHasUnsavedChanges(true);
                            toast.success(`已关联地块：${field.name}，边界已自动加载`);
                          }
                        }
                      }}
                    >
                      <SelectTrigger className="bg-white">
                        <SelectValue placeholder="请选择地块" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="none" disabled>请选择地块</SelectItem>
                        {fields.filter(f => f.status === 'active').length === 0 ? (
                          <SelectItem value="empty" disabled>
                            暂无可用地块，请先在地块管理中添加
                          </SelectItem>
                        ) : (
                          fields.filter(f => f.status === 'active').map(field => (
                            <SelectItem key={field.id} value={field.id}>
                              <div className="flex items-center gap-2">
                                <MapPin className="w-3 h-3" />
                                {field.name} ({field.area}亩 · {field.location})
                              </div>
                            </SelectItem>
                          ))
                        )}
                      </SelectContent>
                    </Select>
                  </div>
                )}
              </div>
            </Card>
          )}

          <Card className="p-4">
            <div className="flex items-center justify-between mb-4">
              <div>
                <h3>规划地图</h3>
                {selectedRoute && selectedRoute.fieldName && (
                  <p className="text-sm text-muted-foreground mt-1">
                    ✓ {selectedRoute.fieldName} - 地块边界已加载
                  </p>
                )}
              </div>
              <div className="flex gap-2">
                <Button
                  size="sm"
                  variant="outline"
                  disabled
                  title="地块边界已自动加载"
                >
                  <Square className="w-4 h-4 mr-1" />
                  ✓ 边界已加载
                </Button>
                <Button
                  size="sm"
                  variant={drawMode === 'obstacle' ? 'default' : 'outline'}
                  onClick={() => {
                    if (!selectedRoute) {
                      toast.error('请先选择或创建一个路线规划');
                      return;
                    }
                    setDrawMode(drawMode === 'obstacle' ? 'none' : 'obstacle');
                    setCurrentDrawing([]);
                  }}
                >
                  <AlertTriangle className="w-4 h-4 mr-1" />
                  标注障碍
                </Button>
              </div>
            </div>

            {drawMode !== 'none' && (
              <div className="mb-4 p-3 bg-info-muted rounded-lg">
                <div className="flex items-center justify-between">
                  <p className="text-sm text-info">
                    点击地图添加点，至少需要3个点
                  </p>
                  <div className="flex gap-2">
                    <Button size="sm" onClick={finishDrawing}>
                      <CheckCircle className="w-4 h-4 mr-1" />
                      完成
                    </Button>
                    <Button size="sm" variant="outline" onClick={cancelDrawing}>
                      取消
                    </Button>
                  </div>
                </div>
              </div>
            )}

            <div className="border rounded-lg overflow-hidden">
              <canvas
                ref={canvasRef}
                width={canvasSize.width}
                height={canvasSize.height}
                className="w-full cursor-crosshair"
                onClick={handleCanvasClick}
              />
            </div>

            <div className="flex items-center justify-between mt-4">
              <div className="flex gap-2">
                <Button size="sm" variant="outline" onClick={() => setZoom(zoom * 1.2)}>
                  <ZoomIn className="w-4 h-4" />
                </Button>
                <Button size="sm" variant="outline" onClick={() => setZoom(zoom / 1.2)}>
                  <ZoomOut className="w-4 h-4" />
                </Button>
                <Button size="sm" variant="outline" onClick={() => { setZoom(1); setOffset({ x: 0, y: 0 }); }}>
                  重置
                </Button>
              </div>

              <div className="flex gap-2 text-sm">
                <label className="flex items-center gap-1">
                  <input
                    type="checkbox"
                    checked={visibleLayers.boundary}
                    onChange={(e) => setVisibleLayers({ ...visibleLayers, boundary: e.target.checked })}
                  />
                  边界
                </label>
                <label className="flex items-center gap-1">
                  <input
                    type="checkbox"
                    checked={visibleLayers.obstacles}
                    onChange={(e) => setVisibleLayers({ ...visibleLayers, obstacles: e.target.checked })}
                  />
                  障碍物
                </label>
                <label className="flex items-center gap-1">
                  <input
                    type="checkbox"
                    checked={visibleLayers.routes}
                    onChange={(e) => setVisibleLayers({ ...visibleLayers, routes: e.target.checked })}
                  />
                  路线
                </label>
              </div>
            </div>
          </Card>
        </div>

        {/* 参数设置 */}
        <div className="space-y-4">
          <Card className="p-4">
            <h3 className="mb-4">作业参数</h3>
            <div className="space-y-3">
              <div>
                <Label htmlFor="rowSpacing">作业行距 (米)</Label>
                <Input
                  id="rowSpacing"
                  type="number"
                  value={routeParams.rowSpacing}
                  onChange={(e) => setRouteParams({...routeParams, rowSpacing: Number(e.target.value)})}
                />
              </div>

              <div>
                <Label htmlFor="direction">耕作方向 (度)</Label>
                <Input
                  id="direction"
                  type="number"
                  value={routeParams.workingDirection}
                  onChange={(e) => setRouteParams({...routeParams, workingDirection: Number(e.target.value)})}
                />
              </div>

              <div>
                <Label htmlFor="workingWidth">作业幅宽 (米)</Label>
                <Input
                  id="workingWidth"
                  type="number"
                  step="0.1"
                  value={routeParams.workingWidth}
                  onChange={(e) => setRouteParams({...routeParams, workingWidth: Number(e.target.value)})}
                />
              </div>

              <div>
                <Label htmlFor="overlap">重叠宽度 (米)</Label>
                <Input
                  id="overlap"
                  type="number"
                  step="0.1"
                  value={routeParams.overlapWidth}
                  onChange={(e) => setRouteParams({...routeParams, overlapWidth: Number(e.target.value)})}
                />
              </div>

              <div>
                <Label htmlFor="turnRadius">转弯半径 (米)</Label>
                <Input
                  id="turnRadius"
                  type="number"
                  value={routeParams.turnRadius}
                  onChange={(e) => setRouteParams({...routeParams, turnRadius: Number(e.target.value)})}
                />
              </div>

              <div>
                <Label>路径模式</Label>
                <Select
                  value={routeParams.pathPattern}
                  onValueChange={(value: any) => setRouteParams({...routeParams, pathPattern: value})}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="parallel">平行往返</SelectItem>
                    <SelectItem value="spiral">螺旋模式</SelectItem>
                    <SelectItem value="zigzag">之字形</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <Button className="w-full" onClick={generateRoute}>
                <Grid3x3 className="w-4 h-4 mr-2" />
                生成路线
              </Button>

              {hasUnsavedChanges && (
                <Button className="w-full bg-success hover:bg-success/90" onClick={saveRoute}>
                  <Save className="w-4 h-4 mr-2" />
                  保存路线
                </Button>
              )}

              <Button 
                variant="outline" 
                className="w-full" 
                onClick={() => setShowExportDialog(true)}
                disabled={!selectedRoute || selectedRoute.stats.totalRows === 0}
              >
                <Download className="w-4 h-4 mr-2" />
                导出路线
              </Button>
            </div>
          </Card>

          {selectedRoute && selectedRoute.stats.totalRows > 0 && (
            <Card className="p-4">
              <h4 className="text-sm mb-3">统计数据</h4>
              <div className="space-y-2 text-sm">
                <div className="flex justify-between">
                  <span className="text-muted-foreground">总行数</span>
                  <span className="font-medium">{selectedRoute.stats.totalRows} 行</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">总里程</span>
                  <span className="font-medium">{selectedRoute.stats.totalDistance} km</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">作业面积</span>
                  <span className="font-medium">{selectedRoute.stats.workingArea} 亩</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">预计用时</span>
                  <span className="font-medium">{selectedRoute.stats.estimatedTime} 小时</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">预计油耗</span>
                  <span className="font-medium">{selectedRoute.stats.fuelEstimate} 升</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">覆盖效率</span>
                  <span className="font-medium text-success">{selectedRoute.stats.efficiency}%</span>
                </div>
              </div>
            </Card>
          )}
        </div>
      </div>

      {/* 功能说明 */}
      <Card className="p-6 bg-info-muted border-info">
        <h4 className="mb-3 text-muted-foreground">🎯 智能路线规划系统</h4>
        <div className="grid md:grid-cols-3 gap-4 text-sm text-muted-foreground">
          <div>
            <h5 className="mb-2">🗺️ GIS地图功能</h5>
            <ul className="space-y-1">
              <li>• 高精度地图显示</li>
              <li>• 绘制农田电子边界</li>
              <li>• 智能标注障碍物</li>
              <li>• 实时可视化预览</li>
            </ul>
          </div>
          <div>
            <h5 className="mb-2">⚙️ 智能规划算法</h5>
            <ul className="space-y-1">
              <li>• 全覆盖无重复路径</li>
              <li>• 自动避让障碍物</li>
              <li>• 多种路径模式</li>
              <li>• 支持手动调整</li>
            </ul>
          </div>
          <div>
            <h5 className="mb-2">📤 导出与应用</h5>
            <ul className="space-y-1">
              <li>• 导出JSON/KML格式</li>
              <li>• 对接自动驾驶系统</li>
              <li>• 减少重漏作业</li>
              <li>• 降低燃油成本</li>
            </ul>
          </div>
        </div>
      </Card>

      {/* 编辑名称对话框 */}
      <Dialog open={showSaveDialog} onOpenChange={setShowSaveDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>编辑路线名称</DialogTitle>
            <DialogDescription>
              为路线设置一个描述性的名称
            </DialogDescription>
          </DialogHeader>
          <div className="py-4">
            <Label htmlFor="routeName">路线名称</Label>
            <Input
              id="routeName"
              value={editingName}
              onChange={(e) => setEditingName(e.target.value)}
              placeholder="例如���东地1号作业路线"
              className="mt-2"
            />
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => {
              setShowSaveDialog(false);
              setEditingRoute(null);
              setEditingName('');
            }}>
              取消
            </Button>
            <Button onClick={saveRouteName}>
              <Save className="w-4 h-4 mr-2" />
              保存
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 移除地块选择对话框，改为在地图区域直接选择 */}

      {/* 导出对话框 */}
      <Dialog open={showExportDialog} onOpenChange={setShowExportDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>导出作业路线</DialogTitle>
            <DialogDescription>
              选择导出格式，可导入至农机自动驾驶系统
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <Button className="w-full" onClick={() => exportRoute('json')}>
              <Download className="w-4 h-4 mr-2" />
              导出为 JSON 格式
            </Button>
            <Button className="w-full" onClick={() => exportRoute('kml')}>
              <Download className="w-4 h-4 mr-2" />
              导出为 KML 格式（Google Earth）
            </Button>
            <Button className="w-full" variant="outline" onClick={() => exportRoute('shp')}>
              <Download className="w-4 h-4 mr-2" />
              导出为 SHP 格式（需要后端支持）
            </Button>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowExportDialog(false)}>
              取消
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
