import { useState, useEffect } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Input } from '../ui/input';
import { Badge } from '../ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../ui/table';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from '../ui/dialog';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '../ui/alert-dialog';
import { Field, FieldTag } from '../../types/field';
import { 
  Search, 
  Filter, 
  Eye, 
  Edit, 
  Trash2, 
  MapPin, 
  FileText,
  Tag as TagIcon,
  History,
  Plus
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';
import { usePagination } from '../../lib/usePagination';
import { DataPagination } from '../ui/data-pagination';
import { FieldVersionHistory } from './FieldVersionHistory';
import { initializeMultipleFieldVersions } from '../../lib/fieldVersionSamples';

interface FieldListProps {
  onEdit?: (fieldId: string) => void;
}

export function FieldList({ onEdit }: FieldListProps) {
  const [fields, setFields] = useState<Field[]>([]);
  const [customTags, setCustomTags] = useState<FieldTag[]>([]);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [soilFilter, setSoilFilter] = useState('all');
  const [plantingModeFilter, setPlantingModeFilter] = useState('all');
  const [showDetailDialog, setShowDetailDialog] = useState(false);
  const [selectedField, setSelectedField] = useState<Field | null>(null);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [deletingId, setDeletingId] = useState<string>('');
  
  // 标签管理
  const [showTagDialog, setShowTagDialog] = useState(false);
  const [selectedFieldForTag, setSelectedFieldForTag] = useState<Field | null>(null);
  const [selectedTags, setSelectedTags] = useState<string[]>([]);
  
  // 版本历史
  const [showVersionHistory, setShowVersionHistory] = useState(false);
  const [selectedFieldForVersion, setSelectedFieldForVersion] = useState<Field | null>(null);

  useEffect(() => {
    loadFields();
    loadCustomTags();
    initializeSampleData();
    
    // 初始化版本历史示例数据
    setTimeout(() => {
      initializeMultipleFieldVersions();
    }, 500);
  }, []);

  const loadFields = () => {
    const data = localStorage.getItem('smart_agriculture_fields');
    if (data) {
      setFields(JSON.parse(data));
    }
  };

  const loadCustomTags = () => {
    const tagsData = localStorage.getItem('smart_agriculture_custom_tags');
    if (tagsData) {
      setCustomTags(JSON.parse(tagsData));
    }
  };

  // 初始化样例数据
  const initializeSampleData = () => {
    const existingData = localStorage.getItem('smart_agriculture_fields');
    if (!existingData || JSON.parse(existingData).length === 0) {
      const sampleFields: Field[] = [
        {
          id: '1',
          code: 'F2024-001',
          name: '东区1号地',
          area: 120.5,
          perimeter: 1380,
          location: '江苏省南京市浦口区',
          coordinates: [
            { lat: 32.0569, lng: 118.6278 },
            { lat: 32.0580, lng: 118.6290 },
            { lat: 32.0572, lng: 118.6302 },
            { lat: 32.0561, lng: 118.6290 }
          ],
          centerPoint: { lat: 32.0570, lng: 118.6290 },
          soilType: 'loamy',
          landUseType: 'farmland',
          plantingMode: 'open-field',
          owner: '张三',
          ownerPhone: '13800138001',
          contractStartDate: '2020-01-01',
          contractEndDate: '2050-12-31',
          contractPeriod: 30,
          certificateNumber: 'CQ2020-0001',
          tags: ['有机种植', '高产示范'],
          category: '优质地块',
          photos: [],
          documents: [],
          status: 'normal',
          createdAt: '2024-01-15T08:00:00Z',
          updatedAt: '2024-01-15T08:00:00Z',
          createdBy: 'admin',
          currentVersion: 1,
          remarks: '优质耕地，适合多种作物种植'
        },
        {
          id: '2',
          code: 'F2024-002',
          name: '西区大棚A',
          area: 85.3,
          perimeter: 1120,
          location: '江苏省南京市江宁区',
          coordinates: [
            { lat: 31.9520, lng: 118.7878 },
            { lat: 31.9530, lng: 118.7890 },
            { lat: 31.9522, lng: 118.7900 },
            { lat: 31.9512, lng: 118.7888 }
          ],
          centerPoint: { lat: 31.9521, lng: 118.7889 },
          soilType: 'sandy',
          landUseType: 'farmland',
          plantingMode: 'greenhouse',
          owner: '李四',
          ownerPhone: '13900139002',
          contractStartDate: '2021-03-01',
          contractEndDate: '2051-02-28',
          contractPeriod: 30,
          certificateNumber: 'CQ2021-0015',
          tags: ['滴灌设施', '智能监测'],
          category: '设施农业',
          photos: [],
          documents: [],
          status: 'normal',
          createdAt: '2024-02-20T09:30:00Z',
          updatedAt: '2024-02-20T09:30:00Z',
          createdBy: 'admin',
          currentVersion: 1,
          remarks: '配备现代化温室大棚和智能灌溉系统'
        },
        {
          id: '3',
          code: 'F2024-003',
          name: '北区果园',
          area: 200.8,
          perimeter: 1850,
          location: '江苏省南京市六合区',
          coordinates: [
            { lat: 32.3420, lng: 118.8420 },
            { lat: 32.3435, lng: 118.8440 },
            { lat: 32.3425, lng: 118.8455 },
            { lat: 32.3410, lng: 118.8435 }
          ],
          centerPoint: { lat: 32.3422, lng: 118.8437 },
          soilType: 'clay',
          landUseType: 'garden',
          plantingMode: 'orchard',
          owner: '王五',
          ownerPhone: '13700137003',
          contractStartDate: '2019-05-01',
          contractEndDate: '2049-04-30',
          contractPeriod: 30,
          certificateNumber: 'CQ2019-0088',
          tags: ['有机种植'],
          category: '经济果园',
          photos: [],
          documents: [],
          status: 'pending',
          createdAt: '2024-03-10T10:15:00Z',
          updatedAt: '2024-03-10T10:15:00Z',
          createdBy: 'admin',
          currentVersion: 1,
          remarks: '种植苹果、梨等优质水果'
        },
        {
          id: '4',
          code: 'F2024-004',
          name: '南区水田1号',
          area: 156.7,
          perimeter: 1620,
          location: '江苏省南京市溧水区',
          coordinates: [
            { lat: 31.6520, lng: 119.0278 },
            { lat: 31.6535, lng: 119.0295 },
            { lat: 31.6525, lng: 119.0310 },
            { lat: 31.6510, lng: 119.0293 }
          ],
          centerPoint: { lat: 31.6522, lng: 119.0294 },
          soilType: 'silt',
          landUseType: 'farmland',
          plantingMode: 'paddy',
          owner: '赵六',
          ownerPhone: '13600136004',
          contractStartDate: '2020-06-01',
          contractEndDate: '2050-05-31',
          contractPeriod: 30,
          certificateNumber: 'CQ2020-0125',
          tags: ['高产示范'],
          category: '水稻种植区',
          photos: [],
          documents: [],
          status: 'normal',
          createdAt: '2024-04-05T11:20:00Z',
          updatedAt: '2024-04-05T11:20:00Z',
          createdBy: 'admin',
          currentVersion: 1,
          remarks: '优质水稻种植基地'
        },
        {
          id: '5',
          code: 'F2024-005',
          name: '中央示范田',
          area: 95.2,
          perimeter: 1250,
          location: '江苏省南京市栖霞区',
          coordinates: [
            { lat: 32.0920, lng: 118.9120 },
            { lat: 32.0932, lng: 118.9135 },
            { lat: 32.0923, lng: 118.9148 },
            { lat: 32.0911, lng: 118.9133 }
          ],
          centerPoint: { lat: 32.0921, lng: 118.9134 },
          soilType: 'loamy',
          landUseType: 'farmland',
          plantingMode: 'open-field',
          owner: '孙七',
          ownerPhone: '13500135005',
          contractStartDate: '2022-01-01',
          contractEndDate: '2052-12-31',
          contractPeriod: 30,
          certificateNumber: 'CQ2022-0056',
          tags: ['有机种植', '高产示范', '智能监测'],
          category: '科技示范',
          photos: [],
          documents: [],
          status: 'normal',
          createdAt: '2024-05-12T14:30:00Z',
          updatedAt: '2024-05-12T14:30:00Z',
          createdBy: 'admin',
          currentVersion: 1,
          remarks: '农业科技示范田，配备全套智能监测设备'
        }
      ];
      
      localStorage.setItem('smart_agriculture_fields', JSON.stringify(sampleFields));
      setFields(sampleFields);
      toast.success('已加载5条样例地块数据');
    }
  };

  const filteredFields = fields.filter(field => {
    const matchKeyword = !searchKeyword ||
      field.code.includes(searchKeyword) ||
      field.name.includes(searchKeyword) ||
      field.owner.includes(searchKeyword);
    
    const matchSoil = soilFilter === 'all' || field.soilType === soilFilter;
    const matchPlanting = plantingModeFilter === 'all' || field.plantingMode === plantingModeFilter;

    return matchKeyword && matchSoil && matchPlanting;
  });

  // 分页
  const pagination = usePagination(filteredFields, 10);

  const handleViewDetail = (field: Field) => {
    setSelectedField(field);
    setShowDetailDialog(true);
  };

  const handleViewVersion = (field: Field) => {
    setSelectedFieldForVersion(field);
    setShowVersionHistory(true);
  };

  const handleDeleteClick = (id: string) => {
    setDeletingId(id);
    setDeleteDialogOpen(true);
  };

  const confirmDelete = () => {
    const updated = fields.filter(f => f.id !== deletingId);
    setFields(updated);
    localStorage.setItem('smart_agriculture_fields', JSON.stringify(updated));
    toast.success('地块删除成功');
    setDeleteDialogOpen(false);
    setDeletingId('');
  };

  // 标签管理功能
  const handleOpenTagDialog = (field: Field) => {
    setSelectedFieldForTag(field);
    setSelectedTags([...(field.tags || [])]);
    setShowTagDialog(true);
  };

  const handleSaveTags = () => {
    if (!selectedFieldForTag) return;

    const updatedFields = fields.map(f => 
      f.id === selectedFieldForTag.id 
        ? { ...f, tags: selectedTags, updatedAt: new Date().toISOString() }
        : f
    );
    
    setFields(updatedFields);
    localStorage.setItem('smart_agriculture_fields', JSON.stringify(updatedFields));
    toast.success('标签更新成功');
    setShowTagDialog(false);
    setSelectedFieldForTag(null);
    setSelectedTags([]);
  };

  const toggleTag = (tagName: string) => {
    if (selectedTags.includes(tagName)) {
      setSelectedTags(selectedTags.filter(t => t !== tagName));
    } else {
      setSelectedTags([...selectedTags, tagName]);
    }
  };

  // 导出数据功能
  const handleExportData = () => {
    const exportData = {
      exportDate: new Date().toISOString(),
      totalFields: filteredFields.length,
      fields: filteredFields.map(field => ({
        编号: field.code,
        名称: field.name,
        面积亩: field.area.toFixed(2),
        周长米: field.perimeter.toFixed(0),
        位置: field.location,
        土壤类型: getSoilTypeLabel(field.soilType),
        种植模式: getPlantingModeLabel(field.plantingMode),
        权属人: field.owner,
        联系电话: field.ownerPhone || '-',
        承包期限: field.contractPeriod ? `${field.contractPeriod}年` : '-',
        标签: field.tags.join(', '),
        状态: field.status === 'normal' ? '正常' : '待确认',
        备注: field.remarks || '-'
      }))
    };

    const dataStr = JSON.stringify(exportData, null, 2);
    const blob = new Blob([dataStr], { type: 'application/json;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `地块数据_${new Date().toISOString().split('T')[0]}.json`;
    link.click();
    URL.revokeObjectURL(url);
    
    toast.success(`已导出 ${filteredFields.length} 条地块数据`);
  };

  const getSoilTypeLabel = (type: string) => {
    const labels: Record<string, string> = {
      sandy: '沙土',
      loamy: '壤土',
      clay: '粘土',
      silt: '淤泥土',
      peat: '泥炭土',
      saline: '盐碱土',
      other: '其他',
    };
    return labels[type] || type;
  };

  const getPlantingModeLabel = (mode: string) => {
    const labels: Record<string, string> = {
      'open-field': '露地',
      'greenhouse': '大棚',
      'orchard': '果园',
      'paddy': '水田',
      'dryland': '旱地',
    };
    return labels[mode] || mode;
  };

  const getSoilTypeBadge = (type: string) => {
    const colors: Record<string, string> = {
      sandy: 'bg-yellow-100 text-yellow-700',
      loamy: 'bg-green-100 text-green-700',
      clay: 'bg-orange-100 text-orange-700',
      silt: 'bg-blue-100 text-blue-700',
      peat: 'bg-purple-100 text-purple-700',
      saline: 'bg-red-100 text-red-700',
      other: 'bg-gray-100 text-gray-700',
    };
    return colors[type] || 'bg-gray-100 text-gray-700';
  };

  // 统计数据
  const stats = {
    total: fields.length,
    totalArea: fields.reduce((sum, f) => sum + f.area, 0),
    averageArea: fields.length > 0 ? fields.reduce((sum, f) => sum + f.area, 0) / fields.length : 0,
    maxArea: fields.length > 0 ? Math.max(...fields.map(f => f.area)) : 0,
    minArea: fields.length > 0 ? Math.min(...fields.map(f => f.area)) : 0,
    bySoilType: fields.reduce((acc, f) => {
      acc[f.soilType] = (acc[f.soilType] || 0) + 1;
      return acc;
    }, {} as Record<string, number>),
    byPlantingMode: fields.reduce((acc, f) => {
      acc[f.plantingMode] = (acc[f.plantingMode] || 0) + 1;
      return acc;
    }, {} as Record<string, number>),
    byStatus: fields.reduce((acc, f) => {
      acc[f.status] = (acc[f.status] || 0) + 1;
      return acc;
    }, {} as Record<string, number>),
  };

  return (
    <div className="space-y-6">

      {/* 统计卡片 */}
      <div className="grid grid-cols-4 gap-4">
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">地块总数</div>
          <div className="mt-2 text-green-600">{stats.total} 个</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">总面积</div>
          <div className="mt-2 text-green-600">{stats.totalArea.toFixed(2)} 亩</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">平均面积</div>
          <div className="mt-2 text-green-600">{stats.averageArea.toFixed(2)} 亩</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">壤土地块</div>
          <div className="mt-2 text-green-600">{stats.bySoilType.loamy || 0} 个</div>
        </Card>
      </div>

      {/* 搜索和筛选 */}
      <Card className="p-4">
        <div className="flex gap-4">
          <div className="flex-1">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground" />
              <Input
                placeholder="搜索地块编号、名称、权属人..."
                value={searchKeyword}
                onChange={(e) => setSearchKeyword(e.target.value)}
                className="pl-10"
              />
            </div>
          </div>
          <Select value={soilFilter} onValueChange={setSoilFilter}>
            <SelectTrigger className="w-40">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">全部土壤</SelectItem>
              <SelectItem value="sandy">沙土</SelectItem>
              <SelectItem value="loamy">壤土</SelectItem>
              <SelectItem value="clay">粘土</SelectItem>
              <SelectItem value="silt">淤泥土</SelectItem>
            </SelectContent>
          </Select>
          <Select value={plantingModeFilter} onValueChange={setPlantingModeFilter}>
            <SelectTrigger className="w-40">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">全部模式</SelectItem>
              <SelectItem value="open-field">露地</SelectItem>
              <SelectItem value="greenhouse">大棚</SelectItem>
              <SelectItem value="orchard">果园</SelectItem>
              <SelectItem value="paddy">水田</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </Card>

      {/* 地块列表 */}
      <Card>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>地块编号</TableHead>
              <TableHead>地块名称</TableHead>
              <TableHead>面积</TableHead>
              <TableHead>土壤类型</TableHead>
              <TableHead>种植模式</TableHead>
              <TableHead>权属人</TableHead>
              <TableHead>状态</TableHead>
              <TableHead>标签</TableHead>
              <TableHead>操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {pagination.paginatedData.length === 0 ? (
              <TableRow>
                <TableCell colSpan={9} className="text-center text-muted-foreground py-8">
                  暂无地块数据
                </TableCell>
              </TableRow>
            ) : (
              pagination.paginatedData.map((field) => (
                <TableRow key={field.id}>
                  <TableCell>
                    <div className="flex items-center gap-2">
                      <MapPin className="w-4 h-4 text-green-600" />
                      <code className="text-xs bg-gray-100 px-2 py-1 rounded">
                        {field.code}
                      </code>
                    </div>
                  </TableCell>
                  <TableCell>
                    <div>
                      <div>{field.name}</div>
                      <p className="text-xs text-muted-foreground">{field.location}</p>
                    </div>
                  </TableCell>
                  <TableCell>
                    <span className="text-green-600">{field.area.toFixed(2)} 亩</span>
                  </TableCell>
                  <TableCell>
                    <Badge className={getSoilTypeBadge(field.soilType)}>
                      {getSoilTypeLabel(field.soilType)}
                    </Badge>
                  </TableCell>
                  <TableCell>
                    {getPlantingModeLabel(field.plantingMode)}
                  </TableCell>
                  <TableCell>{field.owner}</TableCell>
                  <TableCell>
                    <Badge className={field.status === 'normal' ? 'bg-green-100 text-green-700' : 'bg-yellow-100 text-yellow-700'}>
                      {field.status === 'normal' ? '正常' : '待确认'}
                    </Badge>
                  </TableCell>
                  <TableCell>
                    <div className="flex items-center gap-1">
                      <div className="flex flex-wrap gap-1">
                        {field.tags.slice(0, 2).map(tag => {
                          const tagData = customTags.find(t => t.name === tag);
                          return (
                            <Badge 
                              key={tag} 
                              variant="outline" 
                              className="text-xs"
                              style={tagData ? { 
                                borderColor: tagData.color,
                                color: tagData.color 
                              } : {}}
                            >
                              {tag}
                            </Badge>
                          );
                        })}
                        {field.tags.length > 2 && (
                          <Badge variant="outline" className="text-xs">
                            +{field.tags.length - 2}
                          </Badge>
                        )}
                      </div>
                      <Button
                        variant="ghost"
                        size="sm"
                        className="h-6 w-6 p-0"
                        onClick={() => handleOpenTagDialog(field)}
                        title="管理标签"
                      >
                        <Plus className="w-3 h-3" />
                      </Button>
                    </div>
                  </TableCell>
                  <TableCell>
                    <div className="flex gap-1">
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleViewDetail(field)}
                        title="查看详情"
                      >
                        <Eye className="w-4 h-4" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleViewVersion(field)}
                        title="版本历史"
                      >
                        <History className="w-4 h-4 text-blue-600" />
                      </Button>
                      <Button 
                        variant="ghost" 
                        size="sm"
                        onClick={() => onEdit && onEdit(field.id)}
                        title="编辑"
                      >
                        <Edit className="w-4 h-4" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleDeleteClick(field.id)}
                        title="删除"
                      >
                        <Trash2 className="w-4 h-4 text-destructive" />
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>

        {/* 分页 */}
        <DataPagination
          currentPage={pagination.currentPage}
          totalPages={pagination.totalPages}
          pageSize={pagination.pageSize}
          totalItems={filteredFields.length}
          startIndex={pagination.startIndex}
          endIndex={pagination.endIndex}
          onPageChange={pagination.goToPage}
          onPageSizeChange={pagination.setPageSize}
          canPreviousPage={pagination.canPreviousPage}
          canNextPage={pagination.canNextPage}
        />
      </Card>

      {/* 详情对话框 */}
      <Dialog open={showDetailDialog} onOpenChange={setShowDetailDialog}>
        <DialogContent className="max-w-5xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>地块详情</DialogTitle>
            <DialogDescription className="sr-only">
              查看地块详细信息
            </DialogDescription>
          </DialogHeader>
          {selectedField && (
            <div className="space-y-6">
              {/* 地图显示 */}
              <div>
                <Label className="text-xs">地块位置</Label>
                <div className="mt-2 w-full h-80 rounded-lg border-2 bg-gradient-to-br from-green-50 to-blue-50 flex items-center justify-center relative overflow-hidden">
                  {/* 简化的地图占位符，显示边界点信息 */}
                  <div className="absolute inset-0 flex flex-col items-center justify-center p-6">
                    <MapPin className="w-16 h-16 text-green-600 mb-4 opacity-50" />
                    <h4 className="text-green-800 mb-2">地块边界信息</h4>
                    <div className="text-sm text-muted-foreground space-y-1 text-center">
                      <p>📍 位置：{selectedField.location}</p>
                      <p>🗺️ 边界点数：{selectedField.coordinates.length} 个</p>
                      <p>📐 中心坐标：{selectedField.centerPoint.lat.toFixed(6)}, {selectedField.centerPoint.lng.toFixed(6)}</p>
                      <div className="mt-4 p-3 bg-white/80 rounded-md max-w-md">
                        <p className="text-xs text-blue-800">
                          💡 如需查看真实地图，请在编辑模式中查看完整的地图功能
                        </p>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              {/* 基本信息 */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label className="text-xs">地块编号</Label>
                  <div className="field-value-inline">{selectedField.code}</div>
                </div>
                <div>
                  <Label className="text-xs">地块名称</Label>
                  <div className="field-value-inline">{selectedField.name}</div>
                </div>
                <div>
                  <Label className="text-xs">面积</Label>
                  <div className="field-value-inline text-green-600">
                    {selectedField.area.toFixed(2)} 亩
                  </div>
                </div>
                <div>
                  <Label className="text-xs">周长</Label>
                  <div className="field-value-inline">
                    {selectedField.perimeter.toFixed(0)} 米
                  </div>
                </div>
                <div>
                  <Label className="text-xs">土壤类型</Label>
                  <div className="mt-2">
                    <Badge className={getSoilTypeBadge(selectedField.soilType)}>
                      {getSoilTypeLabel(selectedField.soilType)}
                    </Badge>
                  </div>
                </div>
                <div>
                  <Label className="text-xs">种植模式</Label>
                  <div className="field-value-inline">
                    {getPlantingModeLabel(selectedField.plantingMode)}
                  </div>
                </div>
                <div>
                  <Label className="text-xs">地块状态</Label>
                  <div className="mt-2">
                    <Badge className={selectedField.status === 'normal' ? 'bg-green-100 text-green-700' : 'bg-yellow-100 text-yellow-700'}>
                      {selectedField.status === 'normal' ? '正常' : '待确认'}
                    </Badge>
                  </div>
                </div>
                <div>
                  <Label className="text-xs">权属人</Label>
                  <div className="field-value-inline">{selectedField.owner}</div>
                </div>
                <div>
                  <Label className="text-xs">联系电话</Label>
                  <div className="field-value-inline">{selectedField.ownerPhone || '-'}</div>
                </div>
                <div>
                  <Label className="text-xs">确权证号</Label>
                  <div className="field-value-inline">{selectedField.certificateNumber || '-'}</div>
                </div>
                <div className="col-span-2">
                  <Label className="text-xs">承包期限</Label>
                  <div className="field-value-inline">
                    {selectedField.contractStartDate || '-'} 至 {selectedField.contractEndDate || '-'}
                  </div>
                </div>
              </div>
              {selectedField.tags.length > 0 && (
                <div>
                  <Label className="text-xs">地块标签</Label>
                  <div className="mt-2 flex flex-wrap gap-2">
                    {selectedField.tags.map(tag => {
                      const tagData = customTags.find(t => t.name === tag);
                      return (
                        <Badge 
                          key={tag}
                          style={tagData ? {
                            backgroundColor: tagData.color,
                            color: 'white'
                          } : {}}
                        >
                          {tag}
                        </Badge>
                      );
                    })}
                  </div>
                </div>
              )}
              {selectedField.remarks && (
                <div>
                  <Label className="text-xs">备注说明</Label>
                  <div className="field-value">{selectedField.remarks}</div>
                </div>
              )}
            </div>
          )}
          <DialogFooter>
            <Button onClick={() => setShowDetailDialog(false)}>关闭</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 标签管理对话框 */}
      <Dialog open={showTagDialog} onOpenChange={setShowTagDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>管理地块标签</DialogTitle>
            <DialogDescription>
              为 {selectedFieldForTag?.name} 选择标签
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            {customTags.length === 0 ? (
              <div className="text-center text-muted-foreground py-6">
                <TagIcon className="w-12 h-12 mx-auto mb-2 opacity-50" />
                <p>暂无可用标签</p>
                <p className="text-xs mt-1">请先在"地块分类与标签管理"中创建标签</p>
              </div>
            ) : (
              <div className="flex flex-wrap gap-2">
                {customTags.map(tag => {
                  const isSelected = selectedTags.includes(tag.name);
                  return (
                    <Badge
                      key={tag.id}
                      className="cursor-pointer px-3 py-1.5"
                      style={{
                        backgroundColor: isSelected ? tag.color : 'transparent',
                        color: isSelected ? 'white' : tag.color,
                        border: `2px solid ${tag.color}`,
                      }}
                      onClick={() => toggleTag(tag.name)}
                    >
                      {tag.name}
                      {isSelected && ' ✓'}
                    </Badge>
                  );
                })}
              </div>
            )}
            <div className="pt-2">
              <Label className="text-xs">已选择标签</Label>
              <div className="mt-2 min-h-[2rem] flex flex-wrap gap-2">
                {selectedTags.length === 0 ? (
                  <span className="text-sm text-muted-foreground">未选择</span>
                ) : (
                  selectedTags.map(tagName => {
                    const tagData = customTags.find(t => t.name === tagName);
                    return (
                      <Badge
                        key={tagName}
                        style={tagData ? {
                          backgroundColor: tagData.color,
                          color: 'white'
                        } : {}}
                      >
                        {tagName}
                      </Badge>
                    );
                  })
                )}
              </div>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowTagDialog(false)}>
              取消
            </Button>
            <Button className="bg-green-600 hover:bg-green-700" onClick={handleSaveTags}>
              保存
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 删除确认对话框 */}
      <AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>确认删除</AlertDialogTitle>
            <AlertDialogDescription>
              确定要删除该地块吗？此操作无法撤销。
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>取消</AlertDialogCancel>
            <AlertDialogAction
              className="bg-red-600 hover:bg-red-700"
              onClick={confirmDelete}
            >
              删除
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* 版本历史对话框 */}
      {selectedFieldForVersion && (
        <FieldVersionHistory
          field={selectedFieldForVersion}
          open={showVersionHistory}
          onOpenChange={setShowVersionHistory}
          onRestore={(version) => {
            toast.info('版本恢复功能需要在编辑模式中使用');
            setShowVersionHistory(false);
          }}
        />
      )}
    </div>
  );
}

const Label = ({ children, className = '' }: { children: React.ReactNode; className?: string }) => (
  <label className={`text-sm font-medium text-muted-foreground ${className}`}>
    {children}
  </label>
);
