'use client';

import { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Plus, Download, Search, Eye, Edit, Trash2, MapPin, History, X, Tag as TagIcon } from 'lucide-react';
import { Card } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Textarea } from '@/components/ui/textarea';
import { toast } from 'sonner';

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

// 导入分页组件
import { usePagination } from '@/lib/usePagination';
import { DataPagination } from '@/components/ui/data-pagination';

// 导入独立组件
import { LandBasicInfo } from './components/LandBasicInfo';
import { LandOwnershipInfo } from './components/LandOwnershipInfo';
import { LandAttributes } from './components/LandAttributes';
import { LandAttachments } from './components/LandAttachments';
import { LandMapContainer } from './components/LandMapContainer';
import { LandVersionHistory } from './components/LandVersionHistory';

// 地块标签接口
interface LandTag {
  id: string;
  name: string;
  color: string;
  category?: string;
  description?: string;
  createdAt: string;
}

interface Land {
  id: string;
  code: string;
  name: string;
  area: number;
  location: string;
  soilType: string;
  status: string;
  createdAt: string;
  updatedAt: string;
  owner?: string;
  ownerPhone?: string;
  perimeter?: number;
  centerPoint?: { lat: number; lng: number };
  coordinates?: { lat: number; lng: number }[];
  contractStartDate?: string;
  contractEndDate?: string;
  contractPeriod?: number;
  certificateNumber?: string;
  tags?: string[];
  landUseType?: string;
  plantingMode?: string;
  remarks?: string;
}

export default function ManagePage() {
  const [view, setView] = useState<'list' | 'create' | 'edit'>('list');
  const [editingLandId, setEditingLandId] = useState<string | undefined>();
  const [lands, setLands] = useState<Land[]>([]);
  const [customTags, setCustomTags] = useState<LandTag[]>([]);

  // 搜索和筛选
  const [searchKeyword, setSearchKeyword] = useState('');
  const [soilFilter, setSoilFilter] = useState('all');
  const [statusFilter, setStatusFilter] = useState('all');

  // 对话框状态
  const [showDetailDialog, setShowDetailDialog] = useState(false);
  const [selectedLand, setSelectedLand] = useState<Land | null>(null);
  const [showHistoryDialog, setShowHistoryDialog] = useState(false);
  const [selectedLandForHistory, setSelectedLandForHistory] = useState<Land | null>(null);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [deletingId, setDeletingId] = useState<string>('');

  // 标签管理
  const [showTagDialog, setShowTagDialog] = useState(false);
  const [selectedLandForTag, setSelectedLandForTag] = useState<Land | null>(null);
  const [selectedTags, setSelectedTags] = useState<string[]>([]);

  // Load data from localStorage on mount
  useEffect(() => {
    // 临时强制清除现有数据并生成100条测试数据
    localStorage.removeItem('land_archive_data');
    loadLands();
    loadCustomTags();
    initializeSampleData();
    initializeSampleTags();
  }, []);

  const loadLands = () => {
    const savedLands = JSON.parse(localStorage.getItem('land_archive_data') || '[]');
    setLands(savedLands);
  };

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

  // 初始化样例数据
  const initializeSampleData = () => {
    const existingData = localStorage.getItem('land_archive_data');
    // 强制重新生成100条数据用于测试分页功能
    if (!existingData || JSON.parse(existingData).length === 0 || JSON.parse(existingData).length < 100) {
      // 生成100个示例数据
      const sampleLands: Land[] = [];

      // 数据模板
      const districts = ['浦口区', '江宁区', '六合区', '溧水区', '高淳区', '栖霞区', '雨花台区', '秦淮区', '建邺区', '鼓楼区'];
      const landNames = ['东区', '西区', '南区', '北区', '中央区', '示范区', '开发区', '实验区', '生态区', '产业区'];
      const landTypes = ['耕地', '园地', '林地', '草地', '水田', '旱地', '大棚', '果园', '苗圃', '示范基地'];
      const owners = ['张三', '李四', '王五', '赵六', '孙七', '周八', '吴九', '郑十', '陈一', '刘二', '黄三', '杨四', '朱五', '秦六', '尤七', '许八', '何九', '吕十', '施一', '张二', '孔三', '曹四', '严五', '华六', '金七', '魏八', '陶九', '姜十', '戚一', '谢二', '邹三', '喻四', '柏五', '水六', '窦七', '章八', '云九', '苏十', '潘一', '葛二', '奚三', '范四', '彭五', '鲁六', '韦七', '昌八', '马九', '苗十', '凤一', '花二', '方三', '俞四', '任五', '袁六', '柳七', '酆八', '鲍九', '唐十', '费一', '廉二', '岑三', '薛四', '雷五', '贺六', '倪七', '汤八', '滕九', '殷十', '罗一', '毕二', '郝三', '邬四', '安五', '常六', '乐七', '于八', '时九', '傅十', '皮一', '卞二', '齐三', '康四', '伍五', '余六', '元七', '卜八', '顾九', '孟十', '平一', '黄二', '和三', '穆四', '萧五', '尹六', '姚七', '邵八', '湛九', '汪十'];
      const soilTypes = ['loam', 'sand', 'clay', 'silt'];
      const landUseTypes = ['farmland', 'garden', 'forestland', 'grassland'];
      const plantingModes = ['open-field', 'greenhouse', 'orchard', 'paddy', 'dryland'];
      const statusTypes = ['active', 'maintenance'];
      const tagOptions = ['有机种植', '高产示范', '滴灌设施', '智能监测', '生态种植', '科技示范', '节水灌溉', '绿色种植', '无公害种植', '标准化种植', '集约化种植', '机械化种植', '信息化管理', '精准农业', '循环农业'];

      for (let i = 1; i <= 100; i++) {
        const district = districts[Math.floor(Math.random() * districts.length)];
        const landName = landNames[Math.floor(Math.random() * landNames.length)];
        const landType = landTypes[Math.floor(Math.random() * landTypes.length)];
        const owner = owners[i - 1];
        const soilType = soilTypes[Math.floor(Math.random() * soilTypes.length)];
        const landUseType = landUseTypes[Math.floor(Math.random() * landUseTypes.length)];
        const plantingMode = plantingModes[Math.floor(Math.random() * plantingModes.length)];
        const status = statusTypes[Math.floor(Math.random() * statusTypes.length)];

        // 随机生成2-4个标签
        const tagCount = Math.floor(Math.random() * 3) + 2;
        const tags: string[] = [];
        for (let j = 0; j < tagCount; j++) {
          const tag = tagOptions[Math.floor(Math.random() * tagOptions.length)];
          if (!tags.includes(tag)) {
            tags.push(tag);
          }
        }

        // 生成坐标
        const baseLat = 32.0 + (Math.random() - 0.5) * 0.5;
        const baseLng = 118.5 + (Math.random() - 0.5) * 0.8;
        const coordinates = [
          { lat: baseLat + 0.001, lng: baseLng - 0.001 },
          { lat: baseLat + 0.001, lng: baseLng + 0.001 },
          { lat: baseLat - 0.001, lng: baseLng + 0.001 },
          { lat: baseLat - 0.001, lng: baseLng - 0.001 }
        ];

        const area = Number((50 + Math.random() * 200).toFixed(1));
        const perimeter = Math.floor(800 + Math.random() * 1500);

        sampleLands.push({
          id: i.toString(),
          code: `L2024-${i.toString().padStart(3, '0')}`,
          name: `${landName}${landType}${i}号`,
          area: area,
          perimeter: perimeter,
          location: `江苏省南京市${district}`,
          soilType: soilType,
          status: status,
          owner: owner,
          ownerPhone: `1${Math.floor(Math.random() * 9) + 1}${Math.floor(Math.random() * 10)}${Math.floor(Math.random() * 10)}${Math.floor(Math.random() * 10)}${Math.floor(Math.random() * 10)}${Math.floor(Math.random() * 10)}${Math.floor(Math.random() * 10)}${Math.floor(Math.random() * 10)}${Math.floor(Math.random() * 10)}${Math.floor(Math.random() * 10)}`,
          contractStartDate: `${2018 + Math.floor(Math.random() * 6)}-${(Math.floor(Math.random() * 12) + 1).toString().padStart(2, '0')}-01`,
          contractEndDate: `${2048 + Math.floor(Math.random() * 6)}-${(Math.floor(Math.random() * 12) + 1).toString().padStart(2, '0')}-31`,
          contractPeriod: 30,
          certificateNumber: `CQ${2020 + Math.floor(Math.random() * 4)}-${Math.floor(Math.random() * 10000).toString().padStart(4, '0')}`,
          tags: tags,
          landUseType: landUseType,
          plantingMode: plantingMode,
          centerPoint: { lat: baseLat, lng: baseLng },
          coordinates: coordinates,
          createdAt: `2024-${(Math.floor(Math.random() * 12) + 1).toString().padStart(2, '0')}-${(Math.floor(Math.random() * 28) + 1).toString().padStart(2, '0')}T${Math.floor(Math.random() * 24).toString().padStart(2, '0')}:${Math.floor(Math.random() * 60).toString().padStart(2, '0')}:00Z`,
          updatedAt: `2024-${(Math.floor(Math.random() * 12) + 1).toString().padStart(2, '0')}-${(Math.floor(Math.random() * 28) + 1).toString().padStart(2, '0')}T${Math.floor(Math.random() * 24).toString().padStart(2, '0')}:${Math.floor(Math.random() * 60).toString().padStart(2, '0')}:00Z`,
          remarks: `${landType}，面积${area}亩，适合${tags.join('、')}等多种农业发展模式`
        });
      }

      localStorage.setItem('land_archive_data', JSON.stringify(sampleLands));
      setLands(sampleLands);
      toast.success('已加载100条样例地块数据');
    }
  };

  // 初始化样例标签数据
  const initializeSampleTags = () => {
    const existingTags = localStorage.getItem('land_archive_custom_tags');
    if (!existingTags) {
      const sampleTags: LandTag[] = [
        {
          id: 'tag_1',
          name: '有机种植',
          color: '#22c55e', // green-500
          category: '种植方式',
          description: '采用有机农业标准进行种植',
          createdAt: new Date().toISOString()
        },
        {
          id: 'tag_2',
          name: '高产示范',
          color: '#f59e0b', // amber-500
          category: '产量等级',
          description: '高产量示范地块',
          createdAt: new Date().toISOString()
        },
        {
          id: 'tag_3',
          name: '滴灌设施',
          color: '#3b82f6', // blue-500
          category: '基础设施',
          description: '配备滴灌灌溉设施',
          createdAt: new Date().toISOString()
        },
        {
          id: 'tag_4',
          name: '智能监测',
          color: '#8b5cf6', // violet-500
          category: '智能化',
          description: '配备智能监测设备',
          createdAt: new Date().toISOString()
        },
        {
          id: 'tag_5',
          name: '生态种植',
          color: '#10b981', // emerald-500
          category: '种植方式',
          description: '采用生态循环种植模式',
          createdAt: new Date().toISOString()
        },
        {
          id: 'tag_6',
          name: '科技示范',
          color: '#ef4444', // red-500
          category: '示范类型',
          description: '农业科技示范地块',
          createdAt: new Date().toISOString()
        },
        {
          id: 'tag_7',
          name: '节水灌溉',
          color: '#06b6d4', // cyan-500
          category: '灌溉方式',
          description: '采用节水灌溉技术',
          createdAt: new Date().toISOString()
        },
        {
          id: 'tag_8',
          name: '绿色种植',
          color: '#84cc16', // lime-500
          category: '种植方式',
          description: '绿色环保种植方式',
          createdAt: new Date().toISOString()
        }
      ];

      localStorage.setItem('land_archive_custom_tags', JSON.stringify(sampleTags));
      setCustomTags(sampleTags);
    }
  };

  const handleCreateNew = () => {
    setEditingLandId(undefined);
    setView('create');
  };

  const handleEdit = (landId: string) => {
    setEditingLandId(landId);
    setView('edit');
  };

  const handleSave = (land: Land) => {
    if (editingLandId) {
      // Update existing land
      setLands(prev => prev.map(l => l.id === land.id ? land : l));
      toast.success('地块更新成功');
    } else {
      // Create new land
      const newLand = { ...land, id: Date.now().toString(), createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() };
      setLands(prev => [...prev, newLand]);
      toast.success('地块创建成功');
    }
    setView('list');
    setEditingLandId(undefined);

    // Save to localStorage
    const updatedLands = editingLandId
      ? lands.map(l => l.id === land.id ? land : l)
      : [...lands, { ...land, id: Date.now().toString(), createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() }];
    localStorage.setItem('land_archive_data', JSON.stringify(updatedLands));
  };

  const handleCancel = () => {
    setView('list');
    setEditingLandId(undefined);
  };

  const handleExportData = () => {
    const dataStr = JSON.stringify(lands, null, 2);
    const dataBlob = new Blob([dataStr], { type: 'application/json' });
    const url = URL.createObjectURL(dataBlob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `地块档案数据_${new Date().toLocaleDateString()}.json`;
    link.click();
    URL.revokeObjectURL(url);
    toast.success('数据导出成功');
  };

  const handleDelete = (landId: string) => {
    setLands(prev => prev.filter(l => l.id !== landId));
    const updatedLands = lands.filter(l => l.id !== landId);
    localStorage.setItem('land_archive_data', JSON.stringify(updatedLands));
    toast.success('地块删除成功');
  };

  // 查看详情
  const handleViewDetail = (land: Land) => {
    setSelectedLand(land);
    setShowDetailDialog(true);
  };

  // 删除确认
  const handleDeleteClick = (landId: string) => {
    setDeletingId(landId);
    setDeleteDialogOpen(true);
  };

  const confirmDelete = () => {
    const updatedLands = lands.filter(l => l.id !== deletingId);
    setLands(updatedLands);
    localStorage.setItem('land_archive_data', JSON.stringify(updatedLands));
    toast.success('地块删除成功');
    setDeleteDialogOpen(false);
    setDeletingId('');
  };

  // 查看历史数据
  const handleViewHistory = (land: Land) => {
    setSelectedLandForHistory(land);
    setShowHistoryDialog(true);
  };

  // 打开标签管理对话框
  const handleOpenTagDialog = (land: Land) => {
    setSelectedLandForTag(land);
    setSelectedTags([...(land.tags || [])]);
    setShowTagDialog(true);
  };

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

  // 保存标签
  const handleSaveTags = () => {
    if (!selectedLandForTag) return;

    const updatedLands = lands.map(land =>
      land.id === selectedLandForTag.id
        ? { ...land, tags: selectedTags, updatedAt: new Date().toISOString() }
        : land
    );

    setLands(updatedLands);
    localStorage.setItem('land_archive_data', JSON.stringify(updatedLands));
    toast.success('标签更新成功');
    setShowTagDialog(false);
    setSelectedLandForTag(null);
    setSelectedTags([]);
  };

  // 筛选逻辑
  const filteredLands = lands.filter(land => {
    const matchKeyword = !searchKeyword ||
      land.code?.includes(searchKeyword) ||
      land.name.includes(searchKeyword) ||
      land.owner?.includes(searchKeyword);

    const matchSoil = soilFilter === 'all' || land.soilType === soilFilter;
    const matchStatus = statusFilter === 'all' || land.status === statusFilter;

    return matchKeyword && matchSoil && matchStatus;
  });

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

  // 统计数据
  const stats = {
    total: lands.length,
    totalArea: lands.reduce((sum, l) => sum + l.area, 0),
    averageArea: lands.length > 0 ? lands.reduce((sum, l) => sum + l.area, 0) / lands.length : 0,
    maxArea: lands.length > 0 ? Math.max(...lands.map(l => l.area)) : 0,
    minArea: lands.length > 0 ? Math.min(...lands.map(l => l.area)) : 0,
    activeCount: lands.filter(l => l.status === 'active').length,
    maintenanceCount: lands.filter(l => l.status === 'maintenance').length,
    inactiveCount: lands.filter(l => l.status === 'inactive').length,
    bySoilType: lands.reduce((acc, l) => {
      acc[l.soilType] = (acc[l.soilType] || 0) + 1;
      return acc;
    }, {} as Record<string, number>),
  };

  // 辅助函数
  const getSoilTypeLabel = (type: string) => {
    const labels: Record<string, string> = {
      loam: '壤土',
      sand: '沙土',
      clay: '黏土',
      silt: '粉土',
    };
    return labels[type] || type;
  };

  const getSoilTypeBadge = (type: string) => {
    const colors: Record<string, string> = {
      loam: 'bg-green-100 text-green-700',
      sand: 'bg-yellow-100 text-yellow-700',
      clay: 'bg-orange-100 text-orange-700',
      silt: 'bg-blue-100 text-blue-700',
    };
    return colors[type] || 'bg-gray-100 text-gray-700';
  };

  const getStatusBadge = (status: string) => {
    const colors: Record<string, string> = {
      active: 'bg-green-100 text-green-700',
      maintenance: 'bg-yellow-100 text-yellow-700',
      inactive: 'bg-gray-100 text-gray-700',
    };
    return colors[status] || 'bg-gray-100 text-gray-700';
  };

  const getStatusLabel = (status: string) => {
    const labels: Record<string, string> = {
      active: '使用中',
      maintenance: '维护中',
      inactive: '停用',
    };
    return labels[status] || status;
  };

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

  const getPlantingModeBadge = (mode: string) => {
    const colors: Record<string, string> = {
      'open-field': 'bg-blue-100 text-blue-700',
      'greenhouse': 'bg-green-100 text-green-700',
      'orchard': 'bg-orange-100 text-orange-700',
      'paddy': 'bg-cyan-100 text-cyan-700',
      'dryland': 'bg-amber-100 text-amber-700',
    };
    return colors[mode] || 'bg-gray-100 text-gray-700';
  };

  return (
    <div className="space-y-6">
      {view === 'list' ? (
        <>
          <div className="flex items-center justify-between">
            <div>
              <h2 className="text-green-800 text-xl font-semibold">地块档案管理</h2>
              <p className="text-muted-foreground">
                完整的地块档案信息管理，包含录入、查询、编辑和版本历史
              </p>
            </div>
            <div className="flex gap-2">
              <Button onClick={handleCreateNew}>
                <Plus className="w-4 h-4 mr-2" />
                新建地块
              </Button>
              <Button variant="outline" onClick={handleExportData}>
                <Download className="w-4 h-4 mr-2" />
                导出数据
              </Button>
            </div>
          </div>

          {/* 统计卡片 */}
          <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.activeCount} 个</div>
            </Card>
          </div>

          {/* 详细统计 */}
          <div className="grid grid-cols-2 gap-4">
            <Card className="p-4">
              <h3 className="font-medium mb-3">按状态统计</h3>
              <div className="space-y-2">
                <div className="flex justify-between">
                  <span className="text-sm">使用中</span>
                  <Badge className="bg-green-100 text-green-700">{stats.activeCount}</Badge>
                </div>
                <div className="flex justify-between">
                  <span className="text-sm">维护中</span>
                  <Badge className="bg-yellow-100 text-yellow-700">{stats.maintenanceCount}</Badge>
                </div>
                <div className="flex justify-between">
                  <span className="text-sm">停用</span>
                  <Badge className="bg-gray-100 text-gray-700">{stats.inactiveCount}</Badge>
                </div>
              </div>
            </Card>
            <Card className="p-4">
              <h3 className="font-medium mb-3">按土壤类型统计</h3>
              <div className="space-y-2">
                <div className="flex justify-between">
                  <span className="text-sm">壤土</span>
                  <Badge className="bg-green-100 text-green-700">{stats.bySoilType.loam || 0}</Badge>
                </div>
                <div className="flex justify-between">
                  <span className="text-sm">沙土</span>
                  <Badge className="bg-yellow-100 text-yellow-700">{stats.bySoilType.sand || 0}</Badge>
                </div>
                <div className="flex justify-between">
                  <span className="text-sm">黏土</span>
                  <Badge className="bg-orange-100 text-orange-700">{stats.bySoilType.clay || 0}</Badge>
                </div>
              </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="loam">壤土</SelectItem>
                  <SelectItem value="sand">沙土</SelectItem>
                  <SelectItem value="clay">黏土</SelectItem>
                  <SelectItem value="silt">粉土</SelectItem>
                </SelectContent>
              </Select>
              <Select value={statusFilter} onValueChange={setStatusFilter}>
                <SelectTrigger className="w-40">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部状态</SelectItem>
                  <SelectItem value="active">使用中</SelectItem>
                  <SelectItem value="maintenance">维护中</SelectItem>
                  <SelectItem value="inactive">停用</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>
                {filteredLands.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={10} className="text-center text-muted-foreground py-8">
                      {lands.length === 0 ? '暂无地块数据，请点击"新建地块"添加' : '没有符合筛选条件的地块'}
                    </TableCell>
                  </TableRow>
                ) : (
                  pagination.paginatedData.map((land) => (
                    <TableRow key={land.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">
                            {land.code}
                          </code>
                        </div>
                      </TableCell>
                      <TableCell>
                        <div>
                          <div>{land.name}</div>
                          <p className="text-xs text-muted-foreground">{land.location}</p>
                        </div>
                      </TableCell>
                      <TableCell>
                        <span className="text-green-600">{land.area.toFixed(2)} 亩</span>
                      </TableCell>
                      <TableCell>
                        <Badge className={getSoilTypeBadge(land.soilType)}>
                          {getSoilTypeLabel(land.soilType)}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        <Badge className={getPlantingModeBadge(land.plantingMode || 'open-field')}>
                          {getPlantingModeLabel(land.plantingMode || 'open-field')}
                        </Badge>
                      </TableCell>
                      <TableCell>{land.owner || '-'}</TableCell>
                      <TableCell>
                        <Badge className={getStatusBadge(land.status)}>
                          {getStatusLabel(land.status)}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center gap-2">
                          <div className="flex flex-wrap gap-1">
                            {land.tags && land.tags.length > 0 ? (
                              land.tags.slice(0, 2).map((tag, index) => {
                                const tagData = customTags.find(t => t.name === tag);
                                return (
                                  <Badge
                                    key={index}
                                    variant="outline"
                                    className="text-xs"
                                    style={tagData ? {
                                      borderColor: tagData.color,
                                      color: tagData.color
                                    } : {}}
                                  >
                                    {tag}
                                  </Badge>
                                );
                              })
                            ) : (
                              <span className="text-muted-foreground text-sm">-</span>
                            )}
                            {land.tags && land.tags.length > 2 && (
                              <Badge variant="outline" className="text-xs">
                                +{land.tags.length - 2}
                              </Badge>
                            )}
                          </div>
                          <Button
                            variant="ghost"
                            size="sm"
                            className="h-6 w-6 p-0"
                            onClick={() => handleOpenTagDialog(land)}
                            title="管理标签"
                          >
                            <Plus className="w-3 h-3" />
                          </Button>
                        </div>
                      </TableCell>
                      <TableCell>{new Date(land.createdAt).toLocaleDateString()}</TableCell>
                      <TableCell>
                        <div className="flex gap-1">
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleViewDetail(land)}
                            title="查看详情"
                          >
                            <Eye className="w-4 h-4" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleViewHistory(land)}
                            title="历史数据"
                          >
                            <History className="w-4 h-4 text-blue-600" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleEdit(land.id)}
                            title="编辑"
                          >
                            <Edit className="w-4 h-4" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleDeleteClick(land.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={filteredLands.length}
              startIndex={pagination.startIndex}
              endIndex={pagination.endIndex}
              onPageChange={pagination.goToPage}
              onPageSizeChange={pagination.setPageSize}
              canPreviousPage={pagination.canPreviousPage}
              canNextPage={pagination.canNextPage}
              pageSizeOptions={[10, 30, 50, 100]}
            />
          </Card>

          {/* 详情对话框 */}
          <Dialog open={showDetailDialog} onOpenChange={setShowDetailDialog}>
            <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
              <DialogHeader>
                <DialogTitle>地块详情</DialogTitle>
                <DialogDescription className="sr-only">
                  查看地块详细信息
                </DialogDescription>
              </DialogHeader>
              {selectedLand && (
                <div className="space-y-6">
                  {/* 基本信息 */}
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="text-sm font-medium text-muted-foreground">地块编号</label>
                      <div className="mt-1 p-2 bg-gray-50 rounded">{selectedLand.code}</div>
                    </div>
                    <div>
                      <label className="text-sm font-medium text-muted-foreground">地块名称</label>
                      <div className="mt-1 p-2 bg-gray-50 rounded">{selectedLand.name}</div>
                    </div>
                    <div>
                      <label className="text-sm font-medium text-muted-foreground">面积</label>
                      <div className="mt-1 p-2 bg-gray-50 rounded text-green-600">
                        {selectedLand.area.toFixed(2)} 亩
                      </div>
                    </div>
                    <div>
                      <label className="text-sm font-medium text-muted-foreground">周长</label>
                      <div className="mt-1 p-2 bg-gray-50 rounded">
                        {selectedLand.perimeter?.toFixed(0) || '-'} 米
                      </div>
                    </div>
                    <div>
                      <label className="text-sm font-medium text-muted-foreground">土壤类型</label>
                      <div className="mt-2">
                        <Badge className={getSoilTypeBadge(selectedLand.soilType)}>
                          {getSoilTypeLabel(selectedLand.soilType)}
                        </Badge>
                      </div>
                    </div>
                    <div>
                      <label className="text-sm font-medium text-muted-foreground">地块状态</label>
                      <div className="mt-2">
                        <Badge className={getStatusBadge(selectedLand.status)}>
                          {getStatusLabel(selectedLand.status)}
                        </Badge>
                      </div>
                    </div>
                    <div>
                      <label className="text-sm font-medium text-muted-foreground">权属人</label>
                      <div className="mt-1 p-2 bg-gray-50 rounded">{selectedLand.owner || '-'}</div>
                    </div>
                    <div>
                      <label className="text-sm font-medium text-muted-foreground">联系电话</label>
                      <div className="mt-1 p-2 bg-gray-50 rounded">{selectedLand.ownerPhone || '-'}</div>
                    </div>
                    <div>
                      <label className="text-sm font-medium text-muted-foreground">确权证号</label>
                      <div className="mt-1 p-2 bg-gray-50 rounded">{selectedLand.certificateNumber || '-'}</div>
                    </div>
                    <div className="col-span-2">
                      <label className="text-sm font-medium text-muted-foreground">承包期限</label>
                      <div className="mt-1 p-2 bg-gray-50 rounded">
                        {selectedLand.contractStartDate || '-'} 至 {selectedLand.contractEndDate || '-'}
                      </div>
                    </div>
                  </div>

                  {selectedLand.tags && selectedLand.tags.length > 0 && (
                    <div>
                      <label className="text-sm font-medium text-muted-foreground">地块标签</label>
                      <div className="mt-2 flex flex-wrap gap-2">
                        {selectedLand.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>
                  )}

                  {selectedLand.remarks && (
                    <div>
                      <label className="text-sm font-medium text-muted-foreground">备注说明</label>
                      <div className="mt-1 p-2 bg-gray-50 rounded">{selectedLand.remarks}</div>
                    </div>
                  )}

                  <div>
                    <label className="text-sm font-medium text-muted-foreground">位置信息</label>
                    <div className="mt-2 w-full h-60 rounded-lg border-2 bg-gradient-to-br from-green-50 to-blue-50 flex items-center justify-center">
                      <div className="text-center">
                        <MapPin className="w-12 h-12 text-green-600 mx-auto mb-2 opacity-50" />
                        <p className="text-green-800 mb-1">{selectedLand.location}</p>
                        {selectedLand.centerPoint && (
                          <p className="text-xs text-muted-foreground">
                            中心坐标: {selectedLand.centerPoint.lat.toFixed(6)}, {selectedLand.centerPoint.lng.toFixed(6)}
                          </p>
                        )}
                      </div>
                    </div>
                  </div>
                </div>
              )}
              <DialogFooter>
                <Button onClick={() => setShowDetailDialog(false)}>关闭</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>

          {/* 版本历史对话框 */}
          {selectedLandForHistory && (
            <LandVersionHistory
              land={selectedLandForHistory}
              open={showHistoryDialog}
              onOpenChange={setShowHistoryDialog}
              onRestore={(version) => {
                // 处理版本恢复逻辑
                console.log('恢复版本:', version);
              }}
            />
          )}

          {/* 标签管理对话框 */}
          <Dialog open={showTagDialog} onOpenChange={setShowTagDialog}>
            <DialogContent>
              <DialogHeader>
                <DialogTitle>管理地块标签</DialogTitle>
                <DialogDescription>
                  为 {selectedLandForTag?.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>
        </>
      ) : (
        <Card className="p-6">
          <h3 className="text-lg font-semibold mb-4">
            {editingLandId ? '编辑地块' : '新建地块'}
          </h3>
          <LandEditor
            landId={editingLandId}
            onSave={handleSave}
            onCancel={handleCancel}
            lands={lands}
          />
        </Card>
      )}
    </div>
  );
}

function LandEditor({ landId, onSave, onCancel, lands }: {
  landId?: string;
  onSave: (land: Land) => void;
  onCancel: () => void;
  lands: Land[];
}) {
  // UI状态
  const [activeTab, setActiveTab] = useState('basic');

  // 表单数据
  const [formData, setFormData] = useState<Partial<Land>>(() => {
    if (landId) {
      const land = lands.find(l => l.id === landId);
      return land || {
        id: '',
        code: '',
        name: '',
        area: 0,
        perimeter: 0,
        location: '',
        soilType: 'loam',
        status: 'active',
        owner: '',
        ownerPhone: '',
        contractStartDate: '',
        contractEndDate: '',
        contractPeriod: 0,
        certificateNumber: '',
        tags: [],
        landUseType: '',
        remarks: '',
        coordinates: [],
        centerPoint: { lat: 39.9042, lng: 116.4074 },
        createdAt: '',
        updatedAt: ''
      };
    }
    return {
      id: '',
      code: '',
      name: '',
      area: 0,
      perimeter: 0,
      location: '',
      soilType: 'loam',
      status: 'active',
      owner: '',
      ownerPhone: '',
      contractStartDate: '',
      contractEndDate: '',
      contractPeriod: 0,
      certificateNumber: '',
      tags: [],
      landUseType: '',
      remarks: '',
      coordinates: [],
      centerPoint: { lat: 39.9042, lng: 116.4074 },
      createdAt: '',
      updatedAt: ''
    };
  });

  // 地图相关
  const handleCoordinatesChange = (coordinates: GeoCoordinate[], area: number, perimeter: number) => {
    setFormData({
      ...formData,
      coordinates,
      area,
      perimeter,
      centerPoint: coordinates.length > 0 ? {
        lat: coordinates.reduce((sum, c) => sum + c.lat, 0) / coordinates.length,
        lng: coordinates.reduce((sum, c) => sum + c.lng, 0) / coordinates.length
      } : { lat: 39.9042, lng: 116.4074 }
    });
  };

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

    if (!formData.location?.trim()) {
      toast.error('请填写地块位置');
      setActiveTab('basic');
      return;
    }

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

    // 生成地块编号
    const code = landId ? formData.code : `L${new Date().getFullYear()}-${String(lands.length + 1).padStart(3, '0')}`;

    const now = new Date().toISOString();
    const newLand: Land = {
      ...formData as Land,
      code,
      id: landId || Date.now().toString(),
      updatedAt: now,
      createdAt: landId ? formData.createdAt || now : now,
    };

    onSave(newLand);
  };

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

      {/* 主要内容 */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* 左侧：地图 */}
        <div className="lg:col-span-2">
          <LandMapContainer
            coordinates={formData.coordinates || []}
            area={formData.area || 0}
            perimeter={formData.perimeter || 0}
            onCoordinatesChange={handleCoordinatesChange}
          />
        </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">
                <LandBasicInfo
                  formData={formData}
                  onChange={setFormData}
                  isEdit={!!landId}
                />
              </TabsContent>

              {/* 权属信息 */}
              <TabsContent value="ownership">
                <LandOwnershipInfo
                  formData={formData}
                  onChange={setFormData}
                />
              </TabsContent>

              {/* 地块属性 */}
              <TabsContent value="attributes">
                <LandAttributes
                  formData={formData}
                  onChange={setFormData}
                />
              </TabsContent>

              {/* 附件 */}
              <TabsContent value="files">
                <LandAttachments />
              </TabsContent>
            </Tabs>
          </Card>
        </div>
      </div>
    </div>
  );
}