/**
 * GIS编辑工具组件
 * 提供节点编辑、地块分割、地块合并功能
 */

import { useState, useCallback, useRef, useEffect } from 'react';
import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import {
  MousePointer,
  Move,
  Scissors,
  Copy,
  Plus,
  Minus as MinusIcon,
  Trash2,
  Save,
  AlertCircle,
  CheckCircle2,
  RotateCcw
} from 'lucide-react';
import { toast } from 'sonner';
import { DrawField, DrawGeometry } from './drawEditReducer';

export type EditMode = 'none' | 'node' | 'split' | 'merge';

interface EditingToolsProps {
  fields: DrawField[];
  onFieldsUpdate?: (fields: DrawField[]) => void;
  onGeometryChange?: (fieldId: string, geometry: DrawGeometry) => void;
  onSaveRequest?: (geometry: DrawGeometry) => void;
  canvasWidth?: number;
  canvasHeight?: number;
}

export function EditingTools({
  fields: initialFields = [],
  onFieldsUpdate,
  onGeometryChange,
  onSaveRequest,
  canvasWidth = 800,
  canvasHeight = 600
}: EditingToolsProps) {
  const [editMode, setEditMode] = useState<EditMode>('none');
  const [fields, setFields] = useState<DrawField[]>(initialFields);
  const [selectedFieldId, setSelectedFieldId] = useState<string | null>(null);
  const [selectedNodeIndex, setSelectedNodeIndex] = useState<number | null>(null);
  const [isDragging, setIsDragging] = useState(false);
  const [splitLine, setSplitLine] = useState<any[]>([]);
  const [selectedForMerge, setSelectedForMerge] = useState<string[]>([]);

  // 初始化历史记录，包含初始状态
  const [history, setHistory] = useState<DrawField[][]>([JSON.parse(JSON.stringify(initialFields))]);
  const [historyIndex, setHistoryIndex] = useState(0);

  const canvasRef = useRef<HTMLDivElement>(null);

  // 键盘事件处理
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      // Ctrl+Z 撤销
      if (e.ctrlKey && e.key === 'z' && !e.shiftKey) {
        e.preventDefault();
        handleUndo();
      }
      // Ctrl+Y 或 Ctrl+Shift+Z 重做
      else if ((e.ctrlKey && e.key === 'y') || (e.ctrlKey && e.shiftKey && e.key === 'z')) {
        e.preventDefault();
        handleRedo();
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [historyIndex, history]);

  // 添加到历史记录
  const addToHistory = useCallback((newFields: DrawField[]) => {
    const newHistory = history.slice(0, historyIndex + 1);
    newHistory.push(JSON.parse(JSON.stringify(newFields)));
    setHistory(newHistory);
    setHistoryIndex(newHistory.length - 1);
  }, [history, historyIndex]);

  // 撤销
  const handleUndo = () => {
    if (historyIndex > 0) {
      const newIndex = historyIndex - 1;
      setHistoryIndex(newIndex);
      const previousFields = history[newIndex];
      setFields(previousFields);
      if (onFieldsUpdate) onFieldsUpdate(previousFields);
      toast.success(`已撤销，剩余 ${history.length - newIndex - 1} 步可重做`);
    } else {
      toast.info('没有可撤销的操作');
    }
  };

  // 重做
  const handleRedo = () => {
    if (historyIndex < history.length - 1) {
      const newIndex = historyIndex + 1;
      setHistoryIndex(newIndex);
      const nextFields = history[newIndex];
      setFields(nextFields);
      if (onFieldsUpdate) onFieldsUpdate(nextFields);
      toast.success(`已重做，剩余 ${history.length - newIndex - 1} 步可重做`);
    } else {
      toast.info('没有可重做的操作');
    }
  };

  // 计算面积
  const calculateArea = (points: any[]): number => {
    if (points.length < 3) return 0;
    let area = 0;
    for (let i = 0; i < points.length; i++) {
      const j = (i + 1) % points.length;
      area += points[i].x * points[j].y;
      area -= points[j].x * points[i].y;
    }
    const squareMeters = Math.abs(area) * 0.25;
    return squareMeters / 666.67; // 转换为亩
  };

  // 计算周长
  const calculatePerimeter = (points: any[]): number => {
    if (points.length < 2) return 0;
    let perimeter = 0;
    for (let i = 0; i < points.length; i++) {
      const j = (i + 1) % points.length;
      const dx = points[j].x - points[i].x;
      const dy = points[j].y - points[i].y;
      perimeter += Math.sqrt(dx * dx + dy * dy);
    }
    return perimeter * 0.5; // 转换为米
  };

  // 检查点是否在多边形内
  const isPointInPolygon = (point: any, polygon: any[]): boolean => {
    let inside = false;
    for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
      const xi = polygon[i].x, yi = polygon[i].y;
      const xj = polygon[j].x, yj = polygon[j].y;

      const intersect = ((yi > point.y) !== (yj > point.y))
        && (point.x < (xj - xi) * (point.y - yi) / (yj - yi) + xi);
      if (intersect) inside = !inside;
    }
    return inside;
  };

  // 查找点击的地块
  const findFieldAtPoint = (point: any): DrawField | null => {
    for (const field of fields) {
      if (isPointInPolygon(point, field.points)) {
        return field;
      }
    }
    return null;
  };

  // 查找最近的节点
  const findNearestNode = (point: any, fieldId: string): number | null => {
    const field = fields.find(f => f.id === fieldId);
    if (!field) return null;

    let minDist = Infinity;
    let nearestIndex: number | null = null;

    field.points.forEach((node, index) => {
      const dist = Math.sqrt(
        Math.pow(node.x - point.x, 2) + Math.pow(node.y - point.y, 2)
      );
      if (dist < minDist && dist < 15) { // 15px容差
        minDist = dist;
        nearestIndex = index;
      }
    });

    return nearestIndex;
  };

  // 处理鼠标按下
  const handleMouseDown = (e: React.MouseEvent) => {
    if (!canvasRef.current) return;

    const rect = canvasRef.current.getBoundingClientRect();
    const point = {
      x: e.clientX - rect.left,
      y: e.clientY - rect.top
    };

    if (editMode === 'node') {
      // 节点编辑模式
      const field = selectedFieldId ? fields.find(f => f.id === selectedFieldId) : findFieldAtPoint(point);

      if (field) {
        setSelectedFieldId(field.id);
        const nodeIndex = findNearestNode(point, field.id);

        if (nodeIndex !== null) {
          setSelectedNodeIndex(nodeIndex);
          setIsDragging(true);
        }
      }
    } else if (editMode === 'split') {
      // 分割模式 - 绘制分割线
      setSplitLine([...splitLine, point]);
    } else if (editMode === 'merge') {
      // 合并模式 - 选择地块
      const field = findFieldAtPoint(point);
      if (field) {
        if (selectedForMerge.includes(field.id)) {
          setSelectedForMerge(selectedForMerge.filter(id => id !== field.id));
        } else {
          setSelectedForMerge([...selectedForMerge, field.id]);
        }
      }
    }
  };

  // 处理鼠标移动
  const handleMouseMove = (e: React.MouseEvent) => {
    if (!isDragging || !selectedFieldId || selectedNodeIndex === null) return;
    if (!canvasRef.current) return;

    const rect = canvasRef.current.getBoundingClientRect();
    const point = {
      x: e.clientX - rect.left,
      y: e.clientY - rect.top
    };

    const newFields = fields.map(field => {
      if (field.id === selectedFieldId) {
        const newPoints = [...field.points];
        newPoints[selectedNodeIndex] = point;
        return { ...field, points: newPoints };
      }
      return field;
    });

    setFields(newFields);
  };

  // 处理鼠标释放
  const handleMouseUp = () => {
    if (isDragging && selectedFieldId) {
      addToHistory(fields);

      const field = fields.find(f => f.id === selectedFieldId);
      if (field && onGeometryChange) {
        onGeometryChange(field.id, {
          type: 'polygon',
          points: field.points,
          area: calculateArea(field.points),
          perimeter: calculatePerimeter(field.points),
          valid: true
        });
      }

      toast.success('节点位置已更新');
    }

    setIsDragging(false);
    setSelectedNodeIndex(null);
  };

  // 添加节点
  const handleAddNode = () => {
    if (!selectedFieldId || selectedNodeIndex === null) {
      toast.error('请先选择要添加节点的边');
      return;
    }

    const field = fields.find(f => f.id === selectedFieldId);
    if (!field) return;

    const nextIndex = (selectedNodeIndex + 1) % field.points.length;
    const p1 = field.points[selectedNodeIndex];
    const p2 = field.points[nextIndex];

    // 在中点添加新节点
    const newPoint = {
      x: (p1.x + p2.x) / 2,
      y: (p1.y + p2.y) / 2
    };

    const newPoints = [
      ...field.points.slice(0, nextIndex),
      newPoint,
      ...field.points.slice(nextIndex)
    ];

    const newFields = fields.map(f =>
      f.id === selectedFieldId ? { ...f, points: newPoints } : f
    );

    setFields(newFields);
    addToHistory(newFields);
    if (onFieldsUpdate) onFieldsUpdate(newFields);
    toast.success('已添加节点');
  };

  // 删除节点
  const handleDeleteNode = () => {
    if (!selectedFieldId || selectedNodeIndex === null) {
      toast.error('请先选择要删除的节点');
      return;
    }

    const field = fields.find(f => f.id === selectedFieldId);
    if (!field || field.points.length <= 3) {
      toast.error('多边形至少需要3个顶点');
      return;
    }

    const newPoints = field.points.filter((_, index) => index !== selectedNodeIndex);
    const newFields = fields.map(f =>
      f.id === selectedFieldId ? { ...f, points: newPoints } : f
    );

    setFields(newFields);
    addToHistory(newFields);
    setSelectedNodeIndex(null);
    if (onFieldsUpdate) onFieldsUpdate(newFields);
    toast.success('已删除节点');
  };

  // 执行分割
  const handleExecuteSplit = () => {
    if (splitLine.length < 2) {
      toast.error('分割线至少需要2个点');
      return;
    }

    if (!selectedFieldId) {
      toast.error('请先选择要分割的地块');
      return;
    }

    const sourceField = fields.find(f => f.id === selectedFieldId);
    if (!sourceField) {
      toast.error('未找到选中的地块');
      return;
    }

    // 简化的分割实现：将地块分成两部分
    // 使用分割线的中点作为分割参考
    const midPoint = {
      x: (splitLine[0].x + splitLine[splitLine.length - 1].x) / 2,
      y: (splitLine[0].y + splitLine[splitLine.length - 1].y) / 2
    };

    // 计算地块中心
    const centerX = sourceField.points.reduce((sum, p) => sum + p.x, 0) / sourceField.points.length;
    const centerY = sourceField.points.reduce((sum, p) => sum + p.y, 0) / sourceField.points.length;

    // 根据分割线方向分离点
    const isVerticalSplit = Math.abs(splitLine[splitLine.length - 1].y - splitLine[0].y) >
                           Math.abs(splitLine[splitLine.length - 1].x - splitLine[0].x);

    const part1Points: any[] = [];
    const part2Points: any[] = [];

    sourceField.points.forEach(point => {
      if (isVerticalSplit) {
        if (point.x < midPoint.x) {
          part1Points.push(point);
        } else {
          part2Points.push(point);
        }
      } else {
        if (point.y < midPoint.y) {
          part1Points.push(point);
        } else {
          part2Points.push(point);
        }
      }
    });

    // 确保两部分都有足够的点
    if (part1Points.length < 3 || part2Points.length < 3) {
      toast.error('分割失败：分割后的地块顶点数不足');
      setSplitLine([]);
      return;
    }

    // 创建两个新地块
    const field1: DrawField = {
      id: `split-${Date.now()}-1`,
      name: `${sourceField.name}-1`,
      points: part1Points,
      color: sourceField.color || '#22c55e',
      area: calculateArea(part1Points),
      perimeter: calculatePerimeter(part1Points)
    };

    const field2: DrawField = {
      id: `split-${Date.now()}-2`,
      name: `${sourceField.name}-2`,
      points: part2Points,
      color: sourceField.color === '#22c55e' ? '#3b82f6' : '#22c55e',
      area: calculateArea(part2Points),
      perimeter: calculatePerimeter(part2Points)
    };

    // 更新地块列表
    const newFields = [
      ...fields.filter(f => f.id !== selectedFieldId),
      field1,
      field2
    ];

    setFields(newFields);
    addToHistory(newFields);
    setSplitLine([]);
    setSelectedFieldId(null);
    if (onFieldsUpdate) onFieldsUpdate(newFields);

    toast.success('地块分割成功！生成了2个新地块');
  };

  // 执行合并
  const handleExecuteMerge = () => {
    if (selectedForMerge.length < 2) {
      toast.error('请至少选择2个地块进行合并');
      return;
    }

    // 简化实现：这里应该实现多边形合并算法
    const mergedFields = fields.filter(f => selectedForMerge.includes(f.id));
    const allPoints: any[] = [];
    mergedFields.forEach(f => allPoints.push(...f.points));

    // 创建凸包作为合并结果（简化算法）
    const convexHull = computeConvexHull(allPoints);

    const mergedField: DrawField = {
      id: `merged-${Date.now()}`,
      name: `合并地块 (${mergedFields.map(f => f.name).join(' + ')})`,
      points: convexHull,
      color: mergedFields[0].color || '#22c55e',
      area: calculateArea(convexHull),
      perimeter: calculatePerimeter(convexHull)
    };

    const newFields = [
      ...fields.filter(f => !selectedForMerge.includes(f.id)),
      mergedField
    ];

    setFields(newFields);
    addToHistory(newFields);
    setSelectedForMerge([]);
    if (onFieldsUpdate) onFieldsUpdate(newFields);

    toast.success(`已合并 ${mergedFields.length} 个地块`);
  };

  // 计算凸包（Graham扫描算法）
  const computeConvexHull = (points: any[]): any[] => {
    if (points.length < 3) return points;

    // 找到最下最左的点
    let start = points[0];
    points.forEach(p => {
      if (p.y < start.y || (p.y === start.y && p.x < start.x)) {
        start = p;
      }
    });

    // 按极角排序
    const sorted = points.filter(p => p !== start).sort((a, b) => {
      const angleA = Math.atan2(a.y - start.y, a.x - start.x);
      const angleB = Math.atan2(b.y - start.y, b.x - start.x);
      return angleA - angleB;
    });

    const hull: any[] = [start];

    for (const point of sorted) {
      while (hull.length >= 2) {
        const p2 = hull[hull.length - 1];
        const p1 = hull[hull.length - 2];
        const cross = (p2.x - p1.x) * (point.y - p1.y) - (p2.y - p1.y) * (point.x - p1.x);
        if (cross <= 0) {
          hull.pop();
        } else {
          break;
        }
      }
      hull.push(point);
    }

    return hull;
  };

  // 切换编辑模式
  const switchEditMode = (mode: EditMode) => {
    setEditMode(mode);
    setSelectedFieldId(null);
    setSelectedNodeIndex(null);
    setSplitLine([]);
    setSelectedForMerge([]);

    const modeNames: Record<EditMode, string> = {
      none: '查看',
      node: '节点编辑',
      split: '地块分割',
      merge: '地块合并'
    };

    if (mode !== 'none') {
      toast.success(`已切换到${modeNames[mode]}模式`);
    }
  };

  const selectedField = selectedFieldId ? fields.find(f => f.id === selectedFieldId) : null;

  return (
    <div className="grid grid-cols-4 gap-6">
      {/* 左侧工具面板 */}
      <div className="space-y-4">
        {/* 编辑模式 */}
        <Card className="p-4 bg-card">
          <h4 className="mb-3">编辑模式</h4>
          <div className="space-y-2">
            <Button
              variant={editMode === 'none' ? 'default' : 'outline'}
              className="w-full justify-start"
              onClick={() => switchEditMode('none')}
            >
              <MousePointer className="w-4 h-4 mr-2" />
              选择
            </Button>
            <Button
              variant={editMode === 'node' ? 'default' : 'outline'}
              className="w-full justify-start"
              onClick={() => switchEditMode('node')}
            >
              <Move className="w-4 h-4 mr-2" />
              节点编辑
            </Button>
            <Button
              variant={editMode === 'split' ? 'default' : 'outline'}
              className="w-full justify-start"
              onClick={() => switchEditMode('split')}
            >
              <Scissors className="w-4 h-4 mr-2" />
              地块分割
            </Button>
            <Button
              variant={editMode === 'merge' ? 'default' : 'outline'}
              className="w-full justify-start"
              onClick={() => switchEditMode('merge')}
            >
              <Copy className="w-4 h-4 mr-2" />
              地块合并
            </Button>
          </div>
        </Card>

        {/* 节点操作 */}
        {editMode === 'node' && (
          <Card className="p-4 bg-card">
            <h4 className="mb-3">节点操作</h4>
            <div className="space-y-2">
              <Button
                variant="outline"
                className="w-full justify-start"
                onClick={handleAddNode}
                disabled={!selectedFieldId || selectedNodeIndex === null}
              >
                <Plus className="w-4 h-4 mr-2" />
                添加节点
              </Button>
              <Button
                variant="outline"
                className="w-full justify-start text-destructive"
                onClick={handleDeleteNode}
                disabled={!selectedFieldId || selectedNodeIndex === null}
              >
                <MinusIcon className="w-4 h-4 mr-2" />
                删除节点
              </Button>
            </div>
          </Card>
        )}

        {/* 分割操作 */}
        {editMode === 'split' && (
          <Card className="p-4 bg-card">
            <h4 className="mb-3">分割操作</h4>
            <div className="space-y-3">
              <div className="p-3 bg-blue-50 dark:bg-blue-950 border border-blue-200 dark:border-blue-800 rounded-md text-xs text-blue-800 dark:text-blue-200">
                <p className="mb-2">操作步骤：</p>
                <ol className="list-decimal list-inside space-y-1">
                  <li>点击地块选中要分割的地块</li>
                  <li>在画布上绘制分割线（至少2个点）</li>
                  <li>点击"执行分割"按钮</li>
                </ol>
              </div>

              {selectedFieldId && (
                <div className="p-2 bg-green-50 dark:bg-green-950 border border-green-200 dark:border-green-800 rounded-md text-xs text-green-700 dark:text-green-200">
                  ✓ 已选中地块
                </div>
              )}

              <Button
                variant="outline"
                className="w-full justify-start"
                onClick={handleExecuteSplit}
                disabled={splitLine.length < 2 || !selectedFieldId}
              >
                <Scissors className="w-4 h-4 mr-2" />
                执行分割
              </Button>
              <Button
                variant="outline"
                className="w-full justify-start text-destructive"
                onClick={() => setSplitLine([])}
                disabled={splitLine.length === 0}
              >
                <Trash2 className="w-4 h-4 mr-2" />
                清除分割线
              </Button>
            </div>
            <div className="mt-3 space-y-1">
              <div className="text-sm text-muted-foreground">
                分割点: {splitLine.length} 个
              </div>
              {!selectedFieldId && (
                <div className="text-xs text-amber-600">
                  ⚠ 请先点击地块进行选择
                </div>
              )}
            </div>
          </Card>
        )}

        {/* 合并操作 */}
        {editMode === 'merge' && (
          <Card className="p-4 bg-card">
            <h4 className="mb-3">合并操作</h4>
            <div className="space-y-3">
              <div className="p-3 bg-blue-50 dark:bg-blue-950 border border-blue-200 dark:border-blue-800 rounded-md text-xs text-blue-800 dark:text-blue-200">
                <p className="mb-2">操作步骤：</p>
                <ol className="list-decimal list-inside space-y-1">
                  <li>点击要合并的地块（至少2个）</li>
                  <li>查看已选地块数量</li>
                  <li>点击"执行合并"按钮</li>
                </ol>
              </div>

              {selectedForMerge.length > 0 && (
                <div className="p-2 bg-green-50 dark:bg-green-950 border border-green-200 dark:border-green-800 rounded-md text-xs text-green-700 dark:text-green-200">
                  ✓ 已选择 {selectedForMerge.length} 个地块
                  {selectedForMerge.length >= 2 && ' - 可以合并'}
                </div>
              )}

              <Button
                variant="outline"
                className="w-full justify-start"
                onClick={handleExecuteMerge}
                disabled={selectedForMerge.length < 2}
              >
                <Copy className="w-4 h-4 mr-2" />
                执行合并
              </Button>
              <Button
                variant="outline"
                className="w-full justify-start text-destructive"
                onClick={() => setSelectedForMerge([])}
                disabled={selectedForMerge.length === 0}
              >
                <Trash2 className="w-4 h-4 mr-2" />
                取消选择
              </Button>
            </div>
            <div className="mt-3 space-y-1">
              <div className="text-sm text-muted-foreground">
                已选: {selectedForMerge.length} 个地块
              </div>
              {selectedForMerge.length === 1 && (
                <div className="text-xs text-amber-600">
                  ⚠ 至少需要选择2个地块才能合并
                </div>
              )}
            </div>
          </Card>
        )}

        {/* 历史操作 */}
        <Card className="p-4 bg-card">
          <h4 className="mb-3">历史操作</h4>
          <div className="space-y-2">
            <Button
              variant="outline"
              className="w-full justify-start"
              onClick={handleUndo}
              disabled={historyIndex <= 0}
            >
              <RotateCcw className="w-4 h-4 mr-2" />
              撤销 {historyIndex > 0 && `(${historyIndex})`}
            </Button>
            <Button
              variant="outline"
              className="w-full justify-start"
              onClick={handleRedo}
              disabled={historyIndex >= history.length - 1}
            >
              <RotateCcw className="w-4 h-4 mr-2 scale-x-[-1]" />
              重做 {historyIndex < history.length - 1 && `(${history.length - historyIndex - 1})`}
            </Button>
          </div>
          <div className="mt-3 text-xs text-muted-foreground">
            历史步数：{history.length} | 当前位置：{historyIndex + 1}
          </div>
        </Card>

        {/* 保存操作 */}
        <Card className="p-4 bg-card">
          <h4 className="mb-3">保存操作</h4>
          <div className="space-y-2">
            {/* 批量保存分割/合并后的地块 */}
            {fields.length > 0 && (
              <Button
                variant="default"
                className="w-full justify-start bg-green-600 hover:bg-green-700 text-white"
                onClick={() => {
                  // 保存所有新创建的地块（ID包含split或merged的）
                  const newFields = fields.filter(f =>
                    f.id.includes('split-') || f.id.includes('merged-')
                  );

                  if (newFields.length === 0) {
                    toast.info('没有需要保存的新地块');
                    return;
                  }

                  // 保存第一个新地块
                  const geometry: DrawGeometry = {
                    type: 'polygon',
                    points: newFields[0].points,
                    area: calculateArea(newFields[0].points),
                    perimeter: calculatePerimeter(newFields[0].points),
                    valid: true
                  };

                  if (onSaveRequest) {
                    onSaveRequest(geometry);
                    toast.success(`发现 ${newFields.length} 个新地块，正在保存第一个...`);
                  }
                }}
                disabled={!onSaveRequest}
              >
                <Save className="w-4 h-4 mr-2" />
                保存新地块到地块档案
              </Button>
            )}
          </div>
          <div className="mt-2 text-xs text-muted-foreground">
            {fields.filter(f => f.id.includes('split-') || f.id.includes('merged-')).length > 0
              ? `有 ${fields.filter(f => f.id.includes('split-') || f.id.includes('merged-')).length} 个新地块可保存`
              : '请先进行分割或合并操作以创建新地块'}
          </div>
        </Card>

        {/* 地块信息 */}
        {selectedField && (
          <Card className="p-4 bg-card">
            <h4 className="mb-3">地块信息</h4>
            <div className="space-y-2 text-sm">
              <div>
                <div className="text-muted-foreground">名称</div>
                <div className="mt-1">{selectedField.name}</div>
              </div>
              <div>
                <div className="text-muted-foreground">顶点数</div>
                <div className="mt-1">{selectedField.points.length} 个</div>
              </div>
              <div>
                <div className="text-muted-foreground">面积</div>
                <div className="mt-1 text-green-600 dark:text-green-400">
                  {calculateArea(selectedField.points).toFixed(2)} 亩
                </div>
              </div>
              <div>
                <div className="text-muted-foreground">周长</div>
                <div className="mt-1 text-green-600 dark:text-green-400">
                  {calculatePerimeter(selectedField.points).toFixed(0)} 米
                </div>
              </div>
            </div>
          </Card>
        )}
      </div>

      {/* 编辑画布 */}
      <div className="col-span-3">
        <Card className="overflow-hidden bg-card">
          <div
            ref={canvasRef}
            className="relative bg-gradient-to-br from-green-50 to-blue-50 dark:from-green-950 dark:to-blue-950"
            style={{ height: '700px', cursor: isDragging ? 'grabbing' : 'default' }}
            onMouseDown={handleMouseDown}
            onMouseMove={handleMouseMove}
            onMouseUp={handleMouseUp}
          >
            {/* 网格背景 */}
            <div
              className="absolute inset-0"
              style={{
                backgroundImage: `
                  linear-gradient(rgba(0,0,0,0.05) 1px, transparent 1px),
                  linear-gradient(90deg, rgba(0,0,0,0.05) 1px, transparent 1px)
                `,
                backgroundSize: '50px 50px',
                width: canvasWidth,
                height: canvasHeight
              }}
            />

            {/* SVG图层 */}
            <svg
              className="absolute inset-0"
              style={{ width: canvasWidth, height: canvasHeight }}
            >
              {/* 绘制所有地块 */}
              {fields.map(field => {
                const isSelected = field.id === selectedFieldId;
                const isSelectedForMerge = selectedForMerge.includes(field.id);

                return (
                  <g key={field.id}>
                    <polygon
                      points={field.points.map(p => `${p.x},${p.y}`).join(' ')}
                      fill={field.color ? field.color + '40' : '#22c55e40'}
                      stroke={isSelected || isSelectedForMerge ? '#3b82f6' : field.color || '#22c55e'}
                      strokeWidth={isSelected || isSelectedForMerge ? '3' : '2'}
                      opacity={isSelectedForMerge ? '0.8' : '1'}
                    />

                    {/* 地块标签 */}
                    <text
                      x={field.points.reduce((sum, p) => sum + p.x, 0) / field.points.length}
                      y={field.points.reduce((sum, p) => sum + p.y, 0) / field.points.length}
                      textAnchor="middle"
                      fill={field.color || '#22c55e'}
                      className="text-sm pointer-events-none"
                    >
                      {field.name}
                    </text>
                  </g>
                );
              })}

              {/* 分割线 */}
              {splitLine.length > 0 && (
                <polyline
                  points={splitLine.map(p => `${p.x},${p.y}`).join(' ')}
                  fill="none"
                  stroke="#ef4444"
                  strokeWidth="2"
                  strokeDasharray="5,5"
                />
              )}
            </svg>

            {/* 节点编辑模式 - 显示所有节点 */}
            {editMode === 'node' && selectedField && selectedField.points.map((point, index) => {
              const isSelected = index === selectedNodeIndex;
              return (
                <div
                  key={index}
                  className={`absolute w-3 h-3 rounded-full border-2 border-white shadow-lg transform -translate-x-1/2 -translate-y-1/2 cursor-move ${
                    isSelected ? 'bg-blue-600 w-4 h-4' : 'bg-green-600'
                  }`}
                  style={{ left: point.x, top: point.y }}
                >
                  {isSelected && (
                    <div className="absolute top-full left-1/2 transform -translate-x-1/2 mt-1 text-xs bg-white px-1 rounded shadow whitespace-nowrap">
                      节点 {index + 1}
                    </div>
                  )}
                </div>
              );
            })}

            {/* 分割模式 - 显示分割点 */}
            {editMode === 'split' && splitLine.map((point, index) => (
              <div
                key={index}
                className="absolute w-3 h-3 bg-red-600 rounded-full border-2 border-white shadow-lg transform -translate-x-1/2 -translate-y-1/2 pointer-events-none"
                style={{ left: point.x, top: point.y }}
              />
            ))}

            {/* 状态栏 */}
            <div className="absolute bottom-4 left-4 pointer-events-none">
              <Card className="px-3 py-2 bg-background/90 border">
                <div className="flex items-center gap-2 text-sm">
                  <Badge className="bg-blue-600">
                    {editMode === 'none' && '查看模式'}
                    {editMode === 'node' && '节点编辑'}
                    {editMode === 'split' && '地块分割'}
                    {editMode === 'merge' && '地块合并'}
                  </Badge>
                </div>
              </Card>
            </div>
          </div>
        </Card>

        {/* 操作说明 */}
        <Card className="p-4 bg-blue-50 dark:bg-blue-950 border-blue-200 dark:border-blue-800 mt-4">
          <h4 className="text-blue-900 dark:text-blue-100 mb-2">✨ 编辑功能说明</h4>
          <div className="grid grid-cols-2 gap-x-8 gap-y-1 text-sm text-blue-800 dark:text-blue-200">
            <div>• <strong>节点编辑</strong>：点击选择地块，拖动节点调整位置</div>
            <div>• <strong>添加节点</strong>：选择边后点击添加节点按钮</div>
            <div>• <strong>删除节点</strong>：选择节点后点击删除按钮</div>
            <div>• <strong>地块分割</strong>：绘制分割线穿过地块</div>
            <div>• <strong>地块合并</strong>：选择相邻地块进行合并</div>
            <div>• <strong>自动计算</strong>：编辑后面积周长自动更新</div>
          </div>
        </Card>
      </div>
    </div>
  );
}