import { useRef, useState } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Badge } from '../ui/badge';
import { BaseMap, BaseMapRef } from '../shared/BaseMap';
import { GISMapEngine, MapLayer } from '../../lib/gisMapEngine';
import { 
  Map, 
  Layers, 
  MapPin,
  FileJson
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';

// 模拟地块数据
const mockFields = [
  {
    id: 'field-1',
    name: '地块A - 露地种植',
    area: 125.5,
    coordinates: [
      { lng: 116.400, lat: 39.910 },
      { lng: 116.420, lat: 39.910 },
      { lng: 116.420, lat: 39.900 },
      { lng: 116.400, lat: 39.900 },
    ],
    soilType: '沙土',
    plantingMode: '露地',
    color: '#22c55e',
  },
  {
    id: 'field-2',
    name: '地块B - 大棚种植',
    area: 89.3,
    coordinates: [
      { lng: 116.410, lat: 39.895 },
      { lng: 116.425, lat: 39.895 },
      { lng: 116.425, lat: 39.885 },
      { lng: 116.410, lat: 39.885 },
    ],
    soilType: '壤土',
    plantingMode: '大棚',
    color: '#3b82f6',
  },
  {
    id: 'field-3',
    name: '地块C - 果园',
    area: 156.8,
    coordinates: [
      { lng: 116.395, lat: 39.890 },
      { lng: 116.408, lat: 39.890 },
      { lng: 116.408, lat: 39.878 },
      { lng: 116.395, lat: 39.878 },
    ],
    soilType: '粘土',
    plantingMode: '果园',
    color: '#f97316',
  },
];

export function FieldGISMap() {
  const mapRef = useRef<BaseMapRef>(null);
  const [mapEngine, setMapEngine] = useState<GISMapEngine | null>(null);
  const [currentLayer, setCurrentLayer] = useState<MapLayer>('satellite');
  const [selectedField, setSelectedField] = useState<typeof mockFields[0] | null>(null);
  const [showLegend, setShowLegend] = useState(true);

  // 地图就绪回调
  const handleMapReady = (engine: GISMapEngine) => {
    setMapEngine(engine);
    
    // 添加地块多边形
    mockFields.forEach(field => {
      engine.addPolygon({
        id: field.id,
        path: field.coordinates,
        fillColor: field.color,
        strokeColor: field.color.replace('0.3', '1'),
        fillOpacity: 0.3,
        strokeWeight: 2,
        onClick: () => {
          setSelectedField(field);
          toast.success(`已选择: ${field.name}`);
        },
      });
    });

    // 添加地块中心点标记
    mockFields.forEach(field => {
      const centerLat = field.coordinates.reduce((sum, p) => sum + p.lat, 0) / field.coordinates.length;
      const centerLng = field.coordinates.reduce((sum, p) => sum + p.lng, 0) / field.coordinates.length;
      
      engine.addMarker({
        id: `marker-${field.id}`,
        position: { lat: centerLat, lng: centerLng },
        title: field.name,
        color: field.color,
        onClick: () => {
          setSelectedField(field);
          toast.success(`已选择: ${field.name}`);
        },
      });
    });

    toast.success('地图加载成功，已添加3个地块');
  };

  const handleLayerChange = (layer: MapLayer) => {
    setCurrentLayer(layer);
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-green-800">GIS地图管理</h2>
          <p className="text-muted-foreground">
            集成多种底图的智慧农业GIS地图系统
          </p>
        </div>
        <div className="flex gap-2">
          <Button 
            variant="outline"
            onClick={() => setShowLegend(!showLegend)}
          >
            <Layers className="w-4 h-4 mr-2" />
            {showLegend ? '隐藏' : '显示'}图例
          </Button>
        </div>
      </div>

      {/* 地图组件 */}
      <BaseMap
        ref={mapRef}
        provider="leaflet"
        initialCenter={[116.4074, 39.9042]}
        initialZoom={13}
        initialLayer="satellite"
        height="600px"
        showControls={true}
        showLayerSwitcher={true}
        showLegend={showLegend}
        showScale={true}
        showCoordinates={true}
        onMapReady={handleMapReady}
        onLayerChange={handleLayerChange}
      />

      {/* 选中地块信息 */}
      {selectedField && (
        <Card className="p-6 bg-green-50 border-green-200">
          <div className="flex items-start justify-between mb-4">
            <div>
              <h3 className="text-green-800 mb-1">{selectedField.name}</h3>
              <Badge 
                style={{ 
                  backgroundColor: selectedField.color + '20',
                  color: selectedField.color,
                  borderColor: selectedField.color
                }}
                className="border"
              >
                {selectedField.plantingMode}
              </Badge>
            </div>
            <Button
              variant="ghost"
              size="sm"
              onClick={() => setSelectedField(null)}
            >
              关闭
            </Button>
          </div>
          <div className="grid grid-cols-3 gap-4 text-sm">
            <div>
              <span className="text-muted-foreground">地块面积</span>
              <div className="mt-1">{selectedField.area} 亩</div>
            </div>
            <div>
              <span className="text-muted-foreground">土壤类型</span>
              <div className="mt-1">{selectedField.soilType}</div>
            </div>
            <div>
              <span className="text-muted-foreground">种植模式</span>
              <div className="mt-1">{selectedField.plantingMode}</div>
            </div>
          </div>
        </Card>
      )}

      {/* 地图信息面板 */}
      <div className="grid grid-cols-4 gap-4">
        <Card className="p-4">
          <div className="flex items-center gap-3">
            <div className="p-2 bg-green-100 rounded-lg">
              <Map className="w-5 h-5 text-green-600" />
            </div>
            <div>
              <div className="text-sm text-muted-foreground">地图引擎</div>
              <div className="mt-1">Leaflet + OSM</div>
            </div>
          </div>
        </Card>
        <Card className="p-4">
          <div className="flex items-center gap-3">
            <div className="p-2 bg-blue-100 rounded-lg">
              <Layers className="w-5 h-5 text-blue-600" />
            </div>
            <div>
              <div className="text-sm text-muted-foreground">当前图层</div>
              <div className="mt-1">{getLayerName(currentLayer)}</div>
            </div>
          </div>
        </Card>
        <Card className="p-4">
          <div className="flex items-center gap-3">
            <div className="p-2 bg-purple-100 rounded-lg">
              <MapPin className="w-5 h-5 text-purple-600" />
            </div>
            <div>
              <div className="text-sm text-muted-foreground">显示地块</div>
              <div className="mt-1">{mockFields.length} 个</div>
            </div>
          </div>
        </Card>
        <Card className="p-4">
          <div className="flex items-center gap-3">
            <div className="p-2 bg-orange-100 rounded-lg">
              <FileJson className="w-5 h-5 text-orange-600" />
            </div>
            <div>
              <div className="text-sm text-muted-foreground">总面积</div>
              <div className="mt-1">
                {mockFields.reduce((sum, f) => sum + f.area, 0).toFixed(1)} 亩
              </div>
            </div>
          </div>
        </Card>
      </div>

      {/* 功能说明 */}
      <Card className="p-4 bg-blue-50 border-blue-200">
        <h4 className="text-blue-900 mb-2">✨ GIS地图功能特性</h4>
        <div className="grid grid-cols-2 gap-x-8 gap-y-1 text-sm text-blue-800">
          <div className="flex items-center gap-2">
            <div className="w-1.5 h-1.5 rounded-full bg-blue-600"></div>
            <span>支持多种地图底图（卫星、电子、地形、混合）</span>
          </div>
          <div className="flex items-center gap-2">
            <div className="w-1.5 h-1.5 rounded-full bg-blue-600"></div>
            <span>实时切换地图图层，无缝过渡</span>
          </div>
          <div className="flex items-center gap-2">
            <div className="w-1.5 h-1.5 rounded-full bg-blue-600"></div>
            <span>地图缩放、平移、全屏等基础操作</span>
          </div>
          <div className="flex items-center gap-2">
            <div className="w-1.5 h-1.5 rounded-full bg-blue-600"></div>
            <span>比例尺、坐标、图例动态显示</span>
          </div>
          <div className="flex items-center gap-2">
            <div className="w-1.5 h-1.5 rounded-full bg-blue-600"></div>
            <span>地块边界自动渲染，支持交互</span>
          </div>
          <div className="flex items-center gap-2">
            <div className="w-1.5 h-1.5 rounded-full bg-blue-600"></div>
            <span>点击地块查看详细信息</span>
          </div>
        </div>
        <div className="mt-3 pt-3 border-t border-blue-300">
          <p className="text-xs text-blue-700">
            <strong>地图引擎：</strong>默认使用 Leaflet + OpenStreetMap（开源免费），也支持切换到高德地图（需配置Key）
          </p>
        </div>
      </Card>
    </div>
  );
}

function getLayerName(layer: MapLayer): string {
  const names: Record<MapLayer, string> = {
    satellite: '卫星影像',
    street: '电子地图',
    terrain: '地形图',
    hybrid: '混合图层',
  };
  return names[layer];
}
