'use client';

import { useState, useEffect } from 'react';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Card } from '@/components/ui/card';
import {
  History,
  MapPin,
  FileText,
  Clock,
  User,
  RotateCcw,
  Eye,
  GitBranch,
  ChevronRight,
  CheckCircle2
} from 'lucide-react';
import { Land } from '../page';
import { toast } from 'sonner';

// 地块版本历史接口
interface LandVersion {
  id: string;
  landId: string;
  version: number;
  changeType: 'create' | 'update-boundary' | 'update-attributes' | 'merge' | 'split';
  changes: LandVersionChange[];
  coordinates?: { lat: number; lng: number }[]; // 历史边界
  attributes?: Partial<Land>; // 历史属性
  changedBy: string;
  changedAt: string;
  remarks?: string;
}

// 版本变更详情
interface LandVersionChange {
  field: string; // 字段名
  oldValue: any;
  newValue: any;
}

interface LandVersionHistoryProps {
  land: Land;
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onRestore?: (version: LandVersion) => void;
}

export function LandVersionHistory({ land, open, onOpenChange, onRestore }: LandVersionHistoryProps) {
  const [versions, setVersions] = useState<LandVersion[]>([]);
  const [selectedVersion, setSelectedVersion] = useState<LandVersion | null>(null);
  const [showDetailDialog, setShowDetailDialog] = useState(false);

  useEffect(() => {
    if (open && land) {
      loadVersions();
    }
  }, [open, land]);

  const loadVersions = () => {
    try {
      const key = `land_versions_${land.id}`;
      const data = localStorage.getItem(key);
      if (data) {
        const versionList = JSON.parse(data) as LandVersion[];
        // 按版本号降序排列
        setVersions(versionList.sort((a, b) => b.version - a.version));
      } else {
        // 生成示例版本数据
        const sampleVersions: LandVersion[] = [
          {
            id: `version_${land.id}_1`,
            landId: land.id,
            version: 3,
            changeType: 'update-attributes',
            changes: [
              { field: 'tags', oldValue: ['有机种植'], newValue: ['有机种植', '高产示范'] },
              { field: 'soilType', oldValue: 'clay', newValue: 'loam' }
            ],
            coordinates: land.coordinates,
            attributes: land,
            changedBy: '张管理员',
            changedAt: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString(),
            remarks: '更新标签和土壤类型信息'
          },
          {
            id: `version_${land.id}_2`,
            landId: land.id,
            version: 2,
            changeType: 'update-boundary',
            changes: [
              { field: 'coordinates', oldValue: '4个边界点', newValue: '5个边界点' },
              { field: 'area', oldValue: 118.5, newValue: 120.5 }
            ],
            coordinates: land.coordinates,
            attributes: land,
            changedBy: '李测量员',
            changedAt: new Date(Date.now() - 15 * 24 * 60 * 60 * 1000).toISOString(),
            remarks: '重新测量地块边界'
          },
          {
            id: `version_${land.id}_3`,
            landId: land.id,
            version: 1,
            changeType: 'create',
            changes: [
              { field: 'name', oldValue: null, newValue: land.name },
              { field: 'code', oldValue: null, newValue: land.code },
              { field: 'area', oldValue: null, newValue: land.area },
              { field: 'location', oldValue: null, newValue: land.location }
            ],
            coordinates: land.coordinates,
            attributes: land,
            changedBy: '王录入员',
            changedAt: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString(),
            remarks: '创建地块基础信息'
          }
        ];
        setVersions(sampleVersions);
      }
    } catch (error) {
      console.error('加载版本历史失败:', error);
      toast.error('加载版本历史失败');
    }
  };

  const getChangeTypeLabel = (type: LandVersion['changeType']) => {
    const labels = {
      'create': '创建',
      'update-boundary': '边界更新',
      'update-attributes': '属性更新',
      'merge': '合并',
      'split': '分割',
    };
    return labels[type];
  };

  const getChangeTypeBadge = (type: LandVersion['changeType']) => {
    const colors = {
      'create': 'bg-green-100 text-green-700',
      'update-boundary': 'bg-blue-100 text-blue-700',
      'update-attributes': 'bg-purple-100 text-purple-700',
      'merge': 'bg-orange-100 text-orange-700',
      'split': 'bg-pink-100 text-pink-700',
    };
    return colors[type];
  };

  const getFieldLabel = (field: string) => {
    const labels: Record<string, string> = {
      name: '地块名称',
      code: '地块编号',
      area: '面积',
      perimeter: '周长',
      location: '位置',
      soilType: '土壤类型',
      landUseType: '土地利用类型',
      plantingMode: '种植模式',
      owner: '权属人',
      ownerPhone: '联系电话',
      contractPeriod: '承包期限',
      contractStartDate: '承包开始',
      contractEndDate: '承包结束',
      certificateNumber: '确权证号',
      tags: '标签',
      status: '状态',
      coordinates: '边界坐标',
    };
    return labels[field] || field;
  };

  const formatValue = (field: string, value: any) => {
    if (value === null || value === undefined) return '-';

    if (field === 'soilType') {
      const labels: Record<string, string> = {
        loam: '壤土',
        sand: '沙土',
        clay: '黏土',
        silt: '粉土',
        other: '其他',
      };
      return labels[value] || value;
    }

    if (field === 'landUseType') {
      const labels: Record<string, string> = {
        farmland: '耕地',
        garden: '园地',
        forestland: '林地',
        grassland: '草地',
        other: '其他',
      };
      return labels[value] || value;
    }

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

    if (field === 'status') {
      return value === 'active' ? '正常' : '待确认';
    }

    if (field === 'area') {
      return `${value} 亩`;
    }

    if (field === 'perimeter') {
      return `${value} 米`;
    }

    if (field === 'contractPeriod') {
      return `${value} 年`;
    }

    if (field === 'tags' && Array.isArray(value)) {
      return value.join(', ');
    }

    if (field === 'coordinates' && Array.isArray(value)) {
      return `${value.length} 个点`;
    }

    return value;
  };

  const handleViewDetail = (version: LandVersion) => {
    setSelectedVersion(version);
    setShowDetailDialog(true);
  };

  const handleRestore = (version: LandVersion) => {
    if (window.confirm(`确定要恢复到版本 ${version.version} 吗？这将创建一个新版本。`)) {
      onRestore?.(version);
      toast.success('版本已恢复');
      onOpenChange(false);
    }
  };

  const isCurrentVersion = (version: LandVersion) => {
    return version.version === 3; // 假设当前版本是3
  };

  return (
    <>
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <History className="w-5 h-5 text-green-600" />
              版本历史 - {land.name}
            </DialogTitle>
            <DialogDescription className="sr-only">
              查看地块的历史版本和变更记录
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            {versions.length === 0 ? (
              <div className="text-center py-12 text-muted-foreground">
                <History className="w-12 h-12 mx-auto mb-3 opacity-50" />
                <p>暂无版本历史</p>
              </div>
            ) : (
              <div className="relative">
                {/* 时间线 */}
                <div className="absolute left-8 top-0 bottom-0 w-0.5 bg-gray-200" />

                <div className="space-y-6">
                  {versions.map((version, index) => (
                    <div key={version.id} className="relative pl-16">
                      {/* 时间线节点 */}
                      <div className={`absolute left-6 w-5 h-5 rounded-full border-4 border-white ${
                        isCurrentVersion(version)
                          ? 'bg-green-600'
                          : 'bg-gray-400'
                      }`} />

                      <Card className={`p-4 ${isCurrentVersion(version) ? 'border-green-600 border-2' : ''}`}>
                        <div className="flex items-start justify-between mb-3">
                          <div className="flex-1">
                            <div className="flex items-center gap-2 mb-2">
                              <Badge className={getChangeTypeBadge(version.changeType)}>
                                {getChangeTypeLabel(version.changeType)}
                              </Badge>
                              <span className="text-sm text-muted-foreground">
                                版本 {version.version}
                              </span>
                              {isCurrentVersion(version) && (
                                <Badge className="bg-green-600">
                                  <CheckCircle2 className="w-3 h-3 mr-1" />
                                  当前版本
                                </Badge>
                              )}
                            </div>

                            <div className="flex items-center gap-4 text-sm text-muted-foreground">
                              <div className="flex items-center gap-1">
                                <Clock className="w-4 h-4" />
                                {new Date(version.changedAt).toLocaleString('zh-CN')}
                              </div>
                              <div className="flex items-center gap-1">
                                <User className="w-4 h-4" />
                                {version.changedBy}
                              </div>
                            </div>

                            {version.remarks && (
                              <p className="mt-2 text-sm text-muted-foreground">
                                {version.remarks}
                              </p>
                            )}
                          </div>

                          <div className="flex gap-2">
                            <Button
                              size="sm"
                              variant="outline"
                              onClick={() => handleViewDetail(version)}
                            >
                              <Eye className="w-4 h-4 mr-1" />
                              详情
                            </Button>
                            {!isCurrentVersion(version) && (
                              <Button
                                size="sm"
                                variant="outline"
                                onClick={() => handleRestore(version)}
                              >
                                <RotateCcw className="w-4 h-4 mr-1" />
                                恢复
                              </Button>
                            )}
                          </div>
                        </div>

                        {/* 变更摘要 */}
                        {version.changes.length > 0 && (
                          <div className="mt-3 pt-3 border-t">
                            <div className="text-sm space-y-1">
                              {version.changes.slice(0, 3).map((change, idx) => (
                                <div key={idx} className="flex items-center gap-2 text-muted-foreground">
                                  <ChevronRight className="w-4 h-4" />
                                  <span>{getFieldLabel(change.field)}:</span>
                                  <span className="line-through opacity-60">
                                    {formatValue(change.field, change.oldValue)}
                                  </span>
                                  <span>→</span>
                                  <span className="text-foreground">
                                    {formatValue(change.field, change.newValue)}
                                  </span>
                                </div>
                              ))}
                              {version.changes.length > 3 && (
                                <div className="text-xs text-muted-foreground">
                                  还有 {version.changes.length - 3} 项变更...
                                </div>
                              )}
                            </div>
                          </div>
                        )}
                      </Card>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => onOpenChange(false)}>
              关闭
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 版本详情对话框 */}
      {selectedVersion && (
        <Dialog open={showDetailDialog} onOpenChange={setShowDetailDialog}>
          <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle className="flex items-center gap-2">
                <FileText className="w-5 h-5 text-green-600" />
                版本详情 - 版本 {selectedVersion.version}
              </DialogTitle>
              <DialogDescription className="sr-only">
                查看版本的详细变更信息
              </DialogDescription>
            </DialogHeader>

            <div className="space-y-6">
              {/* 版本基本信息 */}
              <Card className="p-4 bg-gray-50">
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label>变更类型</Label>
                    <div className="mt-2">
                      <Badge className={getChangeTypeBadge(selectedVersion.changeType)}>
                        {getChangeTypeLabel(selectedVersion.changeType)}
                      </Badge>
                    </div>
                  </div>
                  <div>
                    <Label>版本号</Label>
                    <div className="mt-2">版本 {selectedVersion.version}</div>
                  </div>
                  <div>
                    <Label>变更时间</Label>
                    <div className="mt-2">
                      {new Date(selectedVersion.changedAt).toLocaleString('zh-CN')}
                    </div>
                  </div>
                  <div>
                    <Label>变更人</Label>
                    <div className="mt-2">{selectedVersion.changedBy}</div>
                  </div>
                  {selectedVersion.remarks && (
                    <div className="col-span-2">
                      <Label>备注</Label>
                      <div className="mt-2">{selectedVersion.remarks}</div>
                    </div>
                  )}
                </div>
              </Card>

              {/* 变更详情 */}
              <div>
                <h4 className="mb-3 flex items-center gap-2">
                  <GitBranch className="w-4 h-4" />
                  变更详情
                </h4>
                <div className="space-y-2">
                  {selectedVersion.changes.map((change, idx) => (
                    <Card key={idx} className="p-3">
                      <div className="flex items-start gap-4">
                        <div className="flex-1">
                          <div className="text-sm mb-2">
                            <Badge variant="outline">{getFieldLabel(change.field)}</Badge>
                          </div>
                          <div className="grid grid-cols-2 gap-4 text-sm">
                            <div>
                              <div className="text-muted-foreground mb-1">原值</div>
                              <div className="p-2 bg-red-50 rounded border border-red-200 line-through">
                                {formatValue(change.field, change.oldValue)}
                              </div>
                            </div>
                            <div>
                              <div className="text-muted-foreground mb-1">新值</div>
                              <div className="p-2 bg-green-50 rounded border border-green-200">
                                {formatValue(change.field, change.newValue)}
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </Card>
                  ))}
                </div>
              </div>

              {/* 边界信息 */}
              {selectedVersion.coordinates && selectedVersion.coordinates.length > 0 && (
                <div>
                  <h4 className="mb-3 flex items-center gap-2">
                    <MapPin className="w-4 h-4" />
                    边界信息
                  </h4>
                  <Card className="p-4 bg-gray-50">
                    <div className="text-sm text-muted-foreground">
                      边界点数量: {selectedVersion.coordinates.length} 个
                    </div>
                  </Card>
                </div>
              )}
            </div>

            <DialogFooter>
              {!isCurrentVersion(selectedVersion) && (
                <Button onClick={() => {
                  handleRestore(selectedVersion);
                  setShowDetailDialog(false);
                }}>
                  <RotateCcw className="w-4 h-4 mr-2" />
                  恢复此版本
                </Button>
              )}
              <Button variant="outline" onClick={() => setShowDetailDialog(false)}>
                关闭
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      )}
    </>
  );
}

const Label = ({ children }: { children: React.ReactNode }) => (
  <label className="text-sm text-muted-foreground">
    {children}
  </label>
);