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 { Textarea } from '../ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import { Badge } from '../ui/badge';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '../ui/dialog';
import { ScrollArea } from '../ui/scroll-area';
import { Separator } from '../ui/separator';
import { Alert, AlertDescription } from '../ui/alert';
import { Field, GeoCoordinate, FieldVersion } from '../../types/field';
import { loadAMapScript } from '../../lib/mapLoader';
import { 
  createFieldVersion, 
  saveFieldVersion, 
  loadFieldVersions,
  restoreFromVersion 
} from '../../lib/fieldVersionManager';
import { FieldVersionHistory } from './FieldVersionHistory';
import { 
  Map, 
  Upload, 
  Save, 
  X, 
  Plus, 
  MapPin, 
  FileText, 
  Image as ImageIcon,
  Layers,
  AlertCircle,
  CheckCircle2,
  Pen,
  History,
  Eye,
  RefreshCw,
  FileType,
  Clock,
  Square
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';

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

interface FieldEditorProps {
  fieldId?: string; // 如果提供fieldId，则为编辑模式
  onSave?: (field: Field) => void;
  onCancel?: () => void;
}

export function FieldEditor({ fieldId, onSave, onCancel }: FieldEditorProps) {
  // 表单数据
  const [formData, setFormData] = useState<Partial<Field>>({
    code: '',
    name: '',
    area: 0,
    perimeter: 0,
    location: '',
    coordinates: [],
    centerPoint: { lat: 39.9042, lng: 116.4074 },
    soilType: 'loamy',
    landUseType: 'farmland',
    plantingMode: 'open-field',
    owner: '',
    tags: [],
    photos: [],
    documents: [],
    status: 'normal',
  });

  // UI状态
  const [activeTab, setActiveTab] = useState('basic');
  const [isMapLoaded, setIsMapLoaded] = useState(false);
  const [mapLayerType, setMapLayerType] = useState<'satellite' | 'street'>('satellite');
  const [drawMode, setDrawMode] = useState<'none' | 'polygon' | 'rectangle'>('none');
  const [tagInput, setTagInput] = useState('');
  const [showVersionHistory, setShowVersionHistory] = useState(false);
  const [versionHistory, setVersionHistory] = useState<FieldVersion[]>([]);

  // 地图相关
  const mapContainerRef = useRef<HTMLDivElement>(null);
  const mapRef = useRef<any>(null);
  const polygonRef = useRef<any>(null);
  const mouseToolRef = useRef<any>(null);
  const [drawPoints, setDrawPoints] = useState<GeoCoordinate[]>([]);

  // 初始化地图
  useEffect(() => {
    initializeMap();
    if (fieldId) {
      loadFieldData(fieldId);
      loadVersionHistory(fieldId);
    }
    return () => {
      if (mapRef.current) {
        mapRef.current.destroy();
      }
    };
  }, []);

  const initializeMap = async () => {
    if (!mapContainerRef.current) return;

    try {
      await loadAMapScript();
      
      if (!window.AMap) {
        // 占位模式：地图SDK未加载，但功能仍然可用
        console.log('💡 使用占位地图模式');
        setIsMapLoaded(true); // 标记为已加载，允许使用其他功能
        toast.info('演示地图模式：可通过文件导入或手动输入坐标数据', { duration: 3000 });
        return;
      }

      const map = new window.AMap.Map(mapContainerRef.current, {
        zoom: 13,
        center: [116.4074, 39.9042],
        viewMode: '3D',
        pitch: 0,
        mapStyle: mapLayerType === 'satellite' ? 'amap://styles/satellite' : 'amap://styles/normal',
      });

      mapRef.current = map;
      setIsMapLoaded(true);

      // 初始化鼠标工具
      const mouseTool = new window.AMap.MouseTool(map);
      mouseToolRef.current = mouseTool;

      toast.success('地图加载成功');
    } catch (error) {
      console.log('ℹ️ 使用占位地图模式');
      // 占位模式下也允许使用其他功能
      setIsMapLoaded(true);
      toast.info('使用占位模式，可通过文件导入或手动输入坐标数据', { duration: 3000 });
    }
  };

  // 加载地块数据（编辑模式）
  const loadFieldData = (id: string) => {
    const fields = JSON.parse(localStorage.getItem('smart_agriculture_fields') || '[]');
    const field = fields.find((f: Field) => f.id === id);
    
    if (field) {
      setFormData(field);
      
      // 在地图上显示边界
      if (field.coordinates && field.coordinates.length > 0 && mapRef.current) {
        drawPolygonOnMap(field.coordinates);
        
        // 调整地图视野
        const bounds = new window.AMap.Bounds();
        field.coordinates.forEach((coord: GeoCoordinate) => {
          bounds.extend([coord.lng, coord.lat]);
        });
        mapRef.current.setBounds(bounds);
      }
    }
  };

  // 加载版本历史
  const loadVersionHistory = (id: string) => {
    const fieldHistory = loadFieldVersions(id);
    setVersionHistory(fieldHistory.sort((a: FieldVersion, b: FieldVersion) => 
      new Date(b.changedAt).getTime() - new Date(a.changedAt).getTime()
    ));
  };

  // 切换地图图层
  const toggleMapLayer = () => {
    if (!window.AMap || !mapRef.current) {
      toast.warning('图层切换需要地图SDK支持', { duration: 3000 });
      return;
    }
    
    const newLayerType = mapLayerType === 'satellite' ? 'street' : 'satellite';
    setMapLayerType(newLayerType);
    
    if (mapRef.current) {
      mapRef.current.setMapStyle(
        newLayerType === 'satellite' ? 'amap://styles/satellite' : 'amap://styles/normal'
      );
      toast.success(`已切换到${newLayerType === 'satellite' ? '卫星图' : '电子地图'}`);
    }
  };

  // 开始绘制
  const startDrawing = (mode: 'polygon' | 'rectangle') => {
    if (!window.AMap || !mouseToolRef.current) {
      toast.warning('手动绘制需要地图SDK支持，请使用文件导入功能', { duration: 4000 });
      return;
    }

    setDrawMode(mode);

    // 清除之前的绘制
    if (polygonRef.current) {
      mapRef.current.remove(polygonRef.current);
      polygonRef.current = null;
    }

    const drawFunction = mode === 'polygon' ? 'polygon' : 'rectangle';
    
    mouseToolRef.current[drawFunction]({
      strokeColor: '#16a34a',
      strokeWeight: 3,
      fillColor: '#22c55e',
      fillOpacity: 0.3,
    });

    mouseToolRef.current.on('draw', (event: any) => {
      const overlay = event.obj;
      const path = overlay.getPath();
      
      const coordinates: GeoCoordinate[] = path.map((lngLat: any) => ({
        lat: lngLat.lat,
        lng: lngLat.lng,
      }));

      setDrawPoints(coordinates);
      polygonRef.current = overlay;

      // 计算面积和周长
      const area = calculateArea(coordinates);
      const perimeter = calculatePerimeter(coordinates);

      setFormData({
        ...formData,
        coordinates,
        area: Number(area.toFixed(2)),
        perimeter: Number(perimeter.toFixed(0)),
        centerPoint: calculateCenter(coordinates),
      });

      mouseToolRef.current.close();
      setDrawMode('none');

      toast.success(`绘制完成！面积：${area.toFixed(2)}亩，周长：${perimeter.toFixed(0)}米`);
    });

    toast.info(`开始绘制${mode === 'polygon' ? '多边形' : '矩形'}，点击地图描点，双击结束`);
  };

  // 在地图上绘制多边形
  const drawPolygonOnMap = (coordinates: GeoCoordinate[]) => {
    if (!mapRef.current || !window.AMap) return;

    // 清除旧的多边形
    if (polygonRef.current) {
      mapRef.current.remove(polygonRef.current);
    }

    const path = coordinates.map(coord => [coord.lng, coord.lat]);
    
    const polygon = new window.AMap.Polygon({
      path,
      strokeColor: '#16a34a',
      strokeWeight: 3,
      fillColor: '#22c55e',
      fillOpacity: 0.3,
    });

    polygon.setMap(mapRef.current);
    polygonRef.current = polygon;
  };

  // 计算多边形面积（返回亩）
  const calculateArea = (coordinates: GeoCoordinate[]): number => {
    if (coordinates.length < 3) return 0;
    
    // 使用Shoelace公式计算面积
    let area = 0;
    for (let i = 0; i < coordinates.length; i++) {
      const j = (i + 1) % coordinates.length;
      area += coordinates[i].lng * coordinates[j].lat;
      area -= coordinates[j].lng * coordinates[i].lat;
    }
    area = Math.abs(area) / 2;
    
    // 将平方度转换为平方米，再转换为亩
    // 1度约等于111km，1亩约等于666.67平方米
    const squareMeters = area * 111000 * 111000;
    const mu = squareMeters / 666.67;
    
    return mu;
  };

  // 计算周长（米）
  const calculatePerimeter = (coordinates: GeoCoordinate[]): number => {
    if (coordinates.length < 2) return 0;
    
    let perimeter = 0;
    for (let i = 0; i < coordinates.length; i++) {
      const j = (i + 1) % coordinates.length;
      const distance = getDistance(coordinates[i], coordinates[j]);
      perimeter += distance;
    }
    
    return perimeter;
  };

  // 计算两点间距离（米）
  const getDistance = (point1: GeoCoordinate, point2: GeoCoordinate): number => {
    const R = 6371000; // 地球半径（米）
    const dLat = (point2.lat - point1.lat) * Math.PI / 180;
    const dLon = (point2.lng - point1.lng) * Math.PI / 180;
    const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
              Math.cos(point1.lat * Math.PI / 180) * Math.cos(point2.lat * Math.PI / 180) *
              Math.sin(dLon/2) * Math.sin(dLon/2);
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    return R * c;
  };

  // 计算中心点
  const calculateCenter = (coordinates: GeoCoordinate[]): { lat: number; lng: number } => {
    const latSum = coordinates.reduce((sum, coord) => sum + coord.lat, 0);
    const lngSum = coordinates.reduce((sum, coord) => sum + coord.lng, 0);
    return {
      lat: latSum / coordinates.length,
      lng: lngSum / coordinates.length,
    };
  };

  // 文件导入
  const handleFileImport = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    const fileExtension = file.name.split('.').pop()?.toLowerCase();
    
    if (!['kml', 'geojson', 'json', 'shp'].includes(fileExtension || '')) {
      toast.error('不支持的文件格式。请上传 KML、GeoJSON 或 SHP 文件');
      return;
    }

    try {
      const text = await file.text();
      let coordinates: GeoCoordinate[] = [];

      if (fileExtension === 'kml') {
        coordinates = parseKML(text);
      } else if (fileExtension === 'geojson' || fileExtension === 'json') {
        coordinates = parseGeoJSON(text);
      } else if (fileExtension === 'shp') {
        toast.info('SHP文件需要服务端解析，当前使用模拟数据');
        coordinates = generateMockCoordinates();
      }

      if (coordinates.length > 0) {
        const area = calculateArea(coordinates);
        const perimeter = calculatePerimeter(coordinates);
        
        setFormData({
          ...formData,
          coordinates,
          area: Number(area.toFixed(2)),
          perimeter: Number(perimeter.toFixed(0)),
          centerPoint: calculateCenter(coordinates),
        });

        // 只在地图SDK可用时绘制多边形和调整视野
        if (window.AMap && mapRef.current) {
          drawPolygonOnMap(coordinates);
          
          // 调整地图视野
          const bounds = new window.AMap.Bounds();
          coordinates.forEach(coord => {
            bounds.extend([coord.lng, coord.lat]);
          });
          mapRef.current.setBounds(bounds);
        }

        toast.success(`成功导入${fileExtension.toUpperCase()}文件！面积：${area.toFixed(2)}亩，${coordinates.length}个点`);
      } else {
        toast.error('文件解析失败，未找到有效的坐标数据');
      }
    } catch (error) {
      console.error('文件导入错误:', error);
      toast.error('文件导入失败，请检查文件格式');
    }

    // 清空input
    event.target.value = '';
  };

  // 解析KML文件
  const parseKML = (kmlText: string): GeoCoordinate[] => {
    try {
      const parser = new DOMParser();
      const xmlDoc = parser.parseFromString(kmlText, 'text/xml');
      const coordinatesElement = xmlDoc.getElementsByTagName('coordinates')[0];
      
      if (!coordinatesElement) return [];

      const coordsText = coordinatesElement.textContent?.trim() || '';
      const coordPairs = coordsText.split(/\s+/);
      
      return coordPairs
        .map(pair => {
          const [lng, lat] = pair.split(',').map(Number);
          return { lat, lng };
        })
        .filter(coord => !isNaN(coord.lat) && !isNaN(coord.lng));
    } catch (error) {
      console.error('KML解析错误:', error);
      return [];
    }
  };

  // 解析GeoJSON文件
  const parseGeoJSON = (geoJsonText: string): GeoCoordinate[] => {
    try {
      const geoJson = JSON.parse(geoJsonText);
      
      let coordinates: number[][][] = [];
      
      if (geoJson.type === 'FeatureCollection' && geoJson.features?.length > 0) {
        const firstFeature = geoJson.features[0];
        if (firstFeature.geometry.type === 'Polygon') {
          coordinates = firstFeature.geometry.coordinates;
        }
      } else if (geoJson.type === 'Feature' && geoJson.geometry?.type === 'Polygon') {
        coordinates = geoJson.geometry.coordinates;
      } else if (geoJson.type === 'Polygon') {
        coordinates = geoJson.coordinates;
      }

      if (coordinates.length > 0 && coordinates[0].length > 0) {
        return coordinates[0].map(([lng, lat]) => ({ lat, lng }));
      }

      return [];
    } catch (error) {
      console.error('GeoJSON解析错误:', error);
      return [];
    }
  };

  // 生成模拟坐标
  const generateMockCoordinates = (): GeoCoordinate[] => {
    const centerLat = 39.9042;
    const centerLng = 116.4074;
    const offset = 0.01;

    return [
      { lat: centerLat + offset, lng: centerLng - offset },
      { lat: centerLat + offset, lng: centerLng + offset },
      { lat: centerLat - offset, lng: centerLng + offset },
      { lat: centerLat - offset, lng: centerLng - offset },
    ];
  };

  // 添加标签
  const handleAddTag = () => {
    if (tagInput.trim() && !formData.tags?.includes(tagInput.trim())) {
      setFormData({
        ...formData,
        tags: [...(formData.tags || []), tagInput.trim()],
      });
      setTagInput('');
      toast.success('标签已添加');
    }
  };

  // 删除标签
  const handleRemoveTag = (tag: string) => {
    setFormData({
      ...formData,
      tags: formData.tags?.filter(t => t !== tag) || [],
    });
  };

  // 保存地块
  const handleSave = () => {
    // 验证必填项
    if (!formData.code || !formData.name) {
      toast.error('请填写地块编号和名称');
      setActiveTab('basic');
      return;
    }

    if (!formData.coordinates || formData.coordinates.length < 3) {
      toast.error('请绘制或导入地块边界（至少3个点）');
      setActiveTab('boundary');
      return;
    }

    if (!formData.owner) {
      toast.error('请填写权属人信息');
      setActiveTab('ownership');
      return;
    }

    try {
      const fields = JSON.parse(localStorage.getItem('smart_agriculture_fields') || '[]');
      const now = new Date().toISOString();
      
      let newField: Field;
      let isUpdate = false;

      if (fieldId) {
        // 编辑模式：保存版本历史
        const oldField = fields.find((f: Field) => f.id === fieldId);
        isUpdate = true;

        newField = {
          ...(formData as Field),
          id: fieldId,
          updatedAt: now,
          currentVersion: (oldField?.currentVersion || 0) + 1,
          createdAt: oldField?.createdAt || now,
          createdBy: oldField?.createdBy || 'admin',
        };

        // 记录版本历史
        saveVersionHistory(fieldId, oldField, newField);

        // 更新地块
        const index = fields.findIndex((f: Field) => f.id === fieldId);
        fields[index] = newField;
      } else {
        // 新建模式
        newField = {
          ...(formData as Field),
          id: `field-${Date.now()}`,
          createdAt: now,
          updatedAt: now,
          createdBy: 'admin',
          currentVersion: 1,
        };

        // 记录创建版本
        saveVersionHistory(newField.id, null, newField);

        fields.push(newField);
      }

      localStorage.setItem('smart_agriculture_fields', JSON.stringify(fields));
      
      toast.success(isUpdate ? '地块信息更新成功！' : '地块信息保存成功！');
      
      if (onSave) {
        onSave(newField);
      }
    } catch (error) {
      console.error('保存失败:', error);
      toast.error('保存失败，请重试');
    }
  };

  // 保存版本历史
  const saveVersionHistory = (fieldId: string, oldField: Field | null, newField: Field) => {
    // 确定变更类型
    let changeType: FieldVersion['changeType'] = 'create';
    if (oldField) {
      // 检查是否有边界变更
      const hasBoundaryChange = JSON.stringify(oldField.coordinates) !== JSON.stringify(newField.coordinates);
      changeType = hasBoundaryChange ? 'update-boundary' : 'update-attributes';
    }

    // 创建版本记录
    const version = createFieldVersion(
      oldField,
      newField,
      changeType,
      'admin', // TODO: 使用实际登录用户
      oldField ? '更新地块信息' : '创建地块'
    );

    // 保存版本
    if (version) {
      saveFieldVersion(version);
      // 重新加载版本历史
      loadVersionHistory(fieldId);
    }
  };

  // 查看历史版本
  const viewHistoryVersion = (version: FieldVersion) => {
    if (version.coordinates) {
      drawPolygonOnMap(version.coordinates);
      
      // 调整地图视野
      const bounds = new window.AMap.Bounds();
      version.coordinates.forEach(coord => {
        bounds.extend([coord.lng, coord.lat]);
      });
      mapRef.current.setBounds(bounds);
    }
    
    toast.info(`正在查看版本 ${version.version}`);
  };

  // 恢复历史版本
  const restoreHistoryVersion = (version: FieldVersion) => {
    try {
      const restored = restoreFromVersion(version);
      setFormData(restored);
      
      if (version.coordinates) {
        drawPolygonOnMap(version.coordinates);
      }

      setShowVersionHistory(false);
      toast.success(`已恢复到版本 ${version.version}，请保存以创建新版本`);
    } catch (error) {
      toast.error('恢复版本失败，数据不完整');
    }
  };

  return (
    <div className="space-y-6">
      {/* 头部 */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-green-800">
            {fieldId ? '编辑地块信息' : '新建地块'}
          </h2>
          <p className="text-sm text-muted-foreground">
            与GIS深度集成的地块编辑器，支持手动绘制、文件导入和版本管理
          </p>
        </div>
        <div className="flex gap-2">
          {fieldId && (
            <Button variant="outline" onClick={() => setShowVersionHistory(true)}>
              <History className="w-4 h-4 mr-2" />
              版本历史 ({versionHistory.length})
            </Button>
          )}
          {onCancel && (
            <Button variant="outline" onClick={onCancel}>
              取消
            </Button>
          )}
          <Button onClick={handleSave}>
            <Save className="w-4 h-4 mr-2" />
            保存地块
          </Button>
        </div>
      </div>

      {/* 主要内容 */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* 左侧：地图 */}
        <div className="lg:col-span-2 space-y-4">
          <Card className="p-6">
            <div className="space-y-4">
              {/* 地图工具栏 */}
              <div className="flex items-center justify-between">
                <h3 className="flex items-center gap-2">
                  <Map className="w-5 h-5 text-green-600" />
                  地块边界绘制
                </h3>
                <div className="flex gap-2">
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={toggleMapLayer}
                    disabled={!window.AMap}
                    title={!window.AMap ? '需要地图SDK支持' : undefined}
                  >
                    <Layers className="w-4 h-4 mr-2" />
                    {mapLayerType === 'satellite' ? '卫星图' : '电子地图'}
                  </Button>
                  <Button
                    variant={drawMode === 'polygon' ? 'default' : 'outline'}
                    size="sm"
                    onClick={() => startDrawing('polygon')}
                    disabled={!window.AMap}
                    title={!window.AMap ? '需要地图SDK支持，请使用文件导入' : undefined}
                  >
                    <Pen className="w-4 h-4 mr-2" />
                    多边形
                  </Button>
                  <Button
                    variant={drawMode === 'rectangle' ? 'default' : 'outline'}
                    size="sm"
                    onClick={() => startDrawing('rectangle')}
                    disabled={!window.AMap}
                    title={!window.AMap ? '需要地图SDK支持，请使用文件导入' : undefined}
                  >
                    <Square className="w-4 h-4 mr-2" />
                    矩形
                  </Button>
                  <div className="relative">
                    <Input
                      type="file"
                      accept=".kml,.geojson,.json,.shp"
                      onChange={handleFileImport}
                      className="absolute inset-0 opacity-0 cursor-pointer"
                    />
                    <Button 
                      variant="outline" 
                      size="sm"
                      className="bg-green-50 hover:bg-green-100 border-green-300"
                    >
                      <Upload className="w-4 h-4 mr-2 text-green-600" />
                      <span className="text-green-700">导入文件</span>
                    </Button>
                  </div>
                </div>
              </div>

              {/* 地图容器 */}
              <div 
                ref={mapContainerRef}
                className="w-full h-[500px] rounded-lg border-2 border-dashed relative bg-gradient-to-br from-green-50 to-blue-50"
              >
                {!window.AMap && isMapLoaded && (
                  <div className="absolute inset-0 flex items-center justify-center p-8">
                    <div className="text-center max-w-md">
                      <Map className="w-16 h-16 mx-auto mb-4 text-green-600 opacity-50" />
                      <h3 className="text-green-800 mb-2">演示地图模式</h3>
                      <p className="text-sm text-muted-foreground mb-4">
                        系统提供完整功能，您可以使用：
                      </p>
                      <ul className="text-sm text-left text-muted-foreground space-y-2">
                        <li className="flex items-start gap-2">
                          <CheckCircle2 className="w-4 h-4 text-green-600 mt-0.5 flex-shrink-0" />
                          <span>导入 KML/GeoJSON/SHP 文件</span>
                        </li>
                        <li className="flex items-start gap-2">
                          <CheckCircle2 className="w-4 h-4 text-green-600 mt-0.5 flex-shrink-0" />
                          <span>手动输入地块属性和坐标数据</span>
                        </li>
                        <li className="flex items-start gap-2">
                          <CheckCircle2 className="w-4 h-4 text-green-600 mt-0.5 flex-shrink-0" />
                          <span>自动计算面积、周长和中心点</span>
                        </li>
                        <li className="flex items-start gap-2">
                          <CheckCircle2 className="w-4 h-4 text-green-600 mt-0.5 flex-shrink-0" />
                          <span>版本历史管理和数据导出</span>
                        </li>
                      </ul>
                      <div className="mt-4 p-3 bg-blue-50 rounded-md">
                        <p className="text-xs text-blue-800">
                          💡 如需启用真实地图，请查看 <code className="px-1 bg-blue-100 rounded">MAP_SDK_QUICK_FIX.md</code>
                        </p>
                      </div>
                    </div>
                  </div>
                )}
                {!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>

              {/* 地图信息 */}
              {formData.coordinates && formData.coordinates.length > 0 && (
                <Alert>
                  <CheckCircle2 className="w-4 h-4 text-green-600" />
                  <AlertDescription>
                    <div className="grid grid-cols-3 gap-4 text-sm">
                      <div>
                        <span className="text-muted-foreground">边界点数：</span>
                        <span className="ml-2 font-medium">{formData.coordinates.length} 个</span>
                      </div>
                      <div>
                        <span className="text-muted-foreground">面积：</span>
                        <span className="ml-2 font-medium text-green-600">{formData.area} 亩</span>
                      </div>
                      <div>
                        <span className="text-muted-foreground">周长：</span>
                        <span className="ml-2 font-medium">{formData.perimeter} 米</span>
                      </div>
                    </div>
                  </AlertDescription>
                </Alert>
              )}

              {/* 文件格式说明 */}
              <Alert className="bg-blue-50 border-blue-200">
                <FileType className="w-4 h-4 text-blue-600" />
                <AlertDescription className="text-sm text-blue-800">
                  <strong>支持的文件格式：</strong>
                  <ul className="mt-2 space-y-1 ml-4 list-disc">
                    <li>KML - Google Earth 标准格式</li>
                    <li>GeoJSON - Web GIS 标准格式</li>
                    <li>SHP - ArcGIS Shapefile 格式（需配合 .shx, .dbf 文件）</li>
                  </ul>
                </AlertDescription>
              </Alert>
            </div>
          </Card>
        </div>

        {/* 右侧：表单 */}
        <div>
          <Card className="p-6">
            <Tabs value={activeTab} onValueChange={setActiveTab}>
              <TabsList className="grid grid-cols-4 mb-4">
                <TabsTrigger value="basic">基本</TabsTrigger>
                <TabsTrigger value="ownership">权属</TabsTrigger>
                <TabsTrigger value="attributes">属性</TabsTrigger>
                <TabsTrigger value="files">附件</TabsTrigger>
              </TabsList>

              {/* 基本信息 */}
              <TabsContent value="basic" className="space-y-4">
                <div>
                  <Label htmlFor="code">地块编号 *</Label>
                  <Input
                    id="code"
                    value={formData.code}
                    onChange={(e) => setFormData({ ...formData, code: e.target.value })}
                    placeholder="如：DB-2024-001"
                  />
                </div>

                <div>
                  <Label htmlFor="name">地块名称 *</Label>
                  <Input
                    id="name"
                    value={formData.name}
                    onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                    placeholder="如：东大田"
                  />
                </div>

                <div>
                  <Label htmlFor="location">所在位置</Label>
                  <Input
                    id="location"
                    value={formData.location}
                    onChange={(e) => setFormData({ ...formData, location: e.target.value })}
                    placeholder="如：北京市朝阳区"
                  />
                </div>

                <div>
                  <Label>地块状态</Label>
                  <Select 
                    value={formData.status} 
                    onValueChange={(value: any) => setFormData({ ...formData, status: value })}
                  >
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="normal">正常</SelectItem>
                      <SelectItem value="pending">待确认</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                <div>
                  <Label htmlFor="remarks">备注</Label>
                  <Textarea
                    id="remarks"
                    value={formData.remarks || ''}
                    onChange={(e) => setFormData({ ...formData, remarks: e.target.value })}
                    placeholder="其他说明信息"
                    rows={3}
                  />
                </div>
              </TabsContent>

              {/* 权属信息 */}
              <TabsContent value="ownership" className="space-y-4">
                <div>
                  <Label htmlFor="owner">权属人 *</Label>
                  <Input
                    id="owner"
                    value={formData.owner}
                    onChange={(e) => setFormData({ ...formData, owner: e.target.value })}
                    placeholder="姓名"
                  />
                </div>

                <div>
                  <Label htmlFor="ownerPhone">联系电话</Label>
                  <Input
                    id="ownerPhone"
                    value={formData.ownerPhone || ''}
                    onChange={(e) => setFormData({ ...formData, ownerPhone: e.target.value })}
                    placeholder="手机号码"
                  />
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label htmlFor="contractStartDate">承包开始</Label>
                    <Input
                      id="contractStartDate"
                      type="date"
                      value={formData.contractStartDate || ''}
                      onChange={(e) => setFormData({ ...formData, contractStartDate: e.target.value })}
                      className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
                    />
                  </div>
                  <div>
                    <Label htmlFor="contractEndDate">承包结束</Label>
                    <Input
                      id="contractEndDate"
                      type="date"
                      value={formData.contractEndDate || ''}
                      onChange={(e) => setFormData({ ...formData, contractEndDate: e.target.value })}
                      className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
                    />
                  </div>
                </div>

                <div>
                  <Label htmlFor="contractPeriod">承包期限（年）</Label>
                  <Input
                    id="contractPeriod"
                    type="number"
                    value={formData.contractPeriod || ''}
                    onChange={(e) => setFormData({ ...formData, contractPeriod: Number(e.target.value) })}
                    placeholder="如：30"
                  />
                </div>

                <div>
                  <Label htmlFor="certificateNumber">确权证号</Label>
                  <Input
                    id="certificateNumber"
                    value={formData.certificateNumber || ''}
                    onChange={(e) => setFormData({ ...formData, certificateNumber: e.target.value })}
                    placeholder="土地确权证书编号"
                  />
                </div>
              </TabsContent>

              {/* 地块属性 */}
              <TabsContent value="attributes" className="space-y-4">
                <div>
                  <Label>土壤类型</Label>
                  <Select 
                    value={formData.soilType} 
                    onValueChange={(value: any) => setFormData({ ...formData, soilType: value })}
                  >
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="sandy">沙土</SelectItem>
                      <SelectItem value="loamy">壤土</SelectItem>
                      <SelectItem value="clay">粘土</SelectItem>
                      <SelectItem value="silt">淤泥土</SelectItem>
                      <SelectItem value="peat">泥炭土</SelectItem>
                      <SelectItem value="saline">盐碱土</SelectItem>
                      <SelectItem value="other">其他</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                <div>
                  <Label>土地利用类型</Label>
                  <Select 
                    value={formData.landUseType} 
                    onValueChange={(value: any) => setFormData({ ...formData, landUseType: value })}
                  >
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="farmland">耕地</SelectItem>
                      <SelectItem value="garden">园地</SelectItem>
                      <SelectItem value="forestland">林地</SelectItem>
                      <SelectItem value="grassland">草地</SelectItem>
                      <SelectItem value="other">其他</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                <div>
                  <Label>种植模式</Label>
                  <Select 
                    value={formData.plantingMode} 
                    onValueChange={(value: any) => setFormData({ ...formData, plantingMode: value })}
                  >
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="open-field">🌾 露地</SelectItem>
                      <SelectItem value="greenhouse">🏠 大棚</SelectItem>
                      <SelectItem value="orchard">🍎 果园</SelectItem>
                      <SelectItem value="paddy">🌊 水田</SelectItem>
                      <SelectItem value="dryland">🌵 旱地</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                <Separator />

                <div>
                  <Label>地块标签</Label>
                  <div className="flex gap-2 mb-2">
                    <Input
                      value={tagInput}
                      onChange={(e) => setTagInput(e.target.value)}
                      placeholder="输入标签"
                      onKeyPress={(e) => e.key === 'Enter' && handleAddTag()}
                    />
                    <Button size="sm" onClick={handleAddTag}>
                      <Plus className="w-4 h-4" />
                    </Button>
                  </div>
                  <div className="flex flex-wrap gap-2">
                    {formData.tags?.map((tag) => (
                      <Badge key={tag} variant="secondary" className="gap-1">
                        {tag}
                        <X 
                          className="w-3 h-3 cursor-pointer" 
                          onClick={() => handleRemoveTag(tag)}
                        />
                      </Badge>
                    ))}
                  </div>
                </div>
              </TabsContent>

              {/* 附件 */}
              <TabsContent value="files" className="space-y-4">
                <div>
                  <Label>地块照片</Label>
                  <div className="mt-2 border-2 border-dashed rounded-lg p-6 text-center hover:border-green-500 transition-colors cursor-pointer">
                    <ImageIcon className="w-8 h-8 mx-auto mb-2 text-muted-foreground" />
                    <p className="text-sm text-muted-foreground">
                      点击上传或拖拽照片到此处
                    </p>
                    <p className="text-xs text-muted-foreground mt-1">
                      支持 JPG、PNG 格式
                    </p>
                  </div>
                </div>

                <Separator />

                <div>
                  <Label>合同文档</Label>
                  <div className="mt-2 space-y-2">
                    <div className="border-2 border-dashed rounded-lg p-4 text-center hover:border-green-500 transition-colors cursor-pointer">
                      <FileText className="w-6 h-6 mx-auto mb-2 text-muted-foreground" />
                      <p className="text-sm text-muted-foreground">
                        上传合同扫描件
                      </p>
                      <p className="text-xs text-muted-foreground mt-1">
                        支持 PDF、图片格式
                      </p>
                    </div>

                    <Alert className="bg-yellow-50 border-yellow-200">
                      <AlertCircle className="w-4 h-4 text-yellow-600" />
                      <AlertDescription className="text-xs text-yellow-800">
                        建议上传：承包合同、确权证书、地块测绘报告等相关文档
                      </AlertDescription>
                    </Alert>
                  </div>
                </div>
              </TabsContent>
            </Tabs>
          </Card>
        </div>
      </div>

      {/* 版本历史对话框 */}
      {fieldId && formData.id && (
        <FieldVersionHistory
          field={formData as Field}
          open={showVersionHistory}
          onOpenChange={setShowVersionHistory}
          onRestore={restoreHistoryVersion}
        />
      )}
    </div>
  );
}
