'use client';

import { useRef, useEffect } from 'react';
import { BaseMap, BaseMapRef } from '@/components/shared/BaseMap';
import { GISMapEngine, Marker, Polygon } from '@/lib/gisMapEngine';
import { MapLayer } from '@/lib/gisMapEngine';
import { Field } from './gisMapReducer';
import { toast } from 'sonner';

interface MapContainerProps {
  currentLayer: MapLayer;
  showLegend: boolean;
  fields: Field[];
  selectedField: Field | null;
  onMapReady: (engine: GISMapEngine) => void;
  onLayerChange: (layer: MapLayer) => void;
  onFieldSelect: (field: Field) => void;
}

export function MapContainer({
  currentLayer,
  showLegend,
  fields,
  selectedField,
  onMapReady,
  onLayerChange,
  onFieldSelect,
}: MapContainerProps) {
  const mapRef = useRef<BaseMapRef>(null);
  const engineRef = useRef<GISMapEngine | null>(null);

  // 地图就绪回调
  const handleMapReady = (engine: GISMapEngine) => {
    engineRef.current = engine;
    onMapReady(engine);

    // 添加地块多边形
    fields.forEach(field => {
      const polygon: Polygon = {
        id: field.id,
        path: field.coordinates,
        fillColor: field.color,
        strokeColor: field.color,
        fillOpacity: 0.3,
        strokeWeight: 2,
        onClick: () => {
          onFieldSelect(field);
          toast.success(`已选择: ${field.name}`);
        },
      };
      engine.addPolygon(polygon);
    });

    // 添加地块中心点标记
    fields.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;

      const marker: Marker = {
        id: `marker-${field.id}`,
        position: { lat: centerLat, lng: centerLng },
        title: field.name,
        color: field.color,
        onClick: () => {
          onFieldSelect(field);
          toast.success(`已选择: ${field.name}`);
        },
      };
      engine.addMarker(marker);
    });

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

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

  // 当选中地块变化时，可以添加高亮效果
  useEffect(() => {
    if (engineRef.current && selectedField) {
      // 这里可以添加选中地块的高亮逻辑
      console.log('选中地块:', selectedField.name);
    }
  }, [selectedField]);

  return (
    <BaseMap
      ref={mapRef}
      provider="leaflet"
      initialCenter={[116.4074, 39.9042]}
      initialZoom={13}
      initialLayer={currentLayer}
      height="600px"
      showControls={true}
      showLayerSwitcher={true}
      showLegend={showLegend}
      showScale={true}
      showCoordinates={true}
      onMapReady={handleMapReady}
      onLayerChange={handleLayerChange}
    />
  );
}