'use client';

import { useReducer } from 'react';
import { Button } from '@/components/ui/button';
import { Layers } from 'lucide-react';
import {
  gisMapReducer,
  initialState,
  GISMapState,
  GISMapAction,
  Field
} from './components/gisMapReducer';
import { MapContainer } from './components/MapContainer';
import { SelectedFieldInfo } from './components/SelectedFieldInfo';
import { MapInfoPanel } from './components/MapInfoPanel';
import { FeatureDescription } from './components/FeatureDescription';

export default function GISMapPage() {
  const [state, dispatch] = useReducer(gisMapReducer, initialState);

  // 地图就绪回调
  const handleMapReady = (engine: any) => {
    dispatch({ type: 'SET_MAP_ENGINE', payload: engine });
  };

  // 图层切换
  const handleLayerChange = (layer: any) => {
    dispatch({ type: 'SET_CURRENT_LAYER', payload: layer });
  };

  // 地块选择
  const handleFieldSelect = (field: Field) => {
    dispatch({ type: 'SET_SELECTED_FIELD', payload: field });
  };

  // 切换图例显示
  const handleToggleLegend = () => {
    dispatch({ type: 'TOGGLE_LEGEND' });
  };

  // 关闭选中地块
  const handleCloseSelectedField = () => {
    dispatch({ type: 'SET_SELECTED_FIELD', payload: null });
  };

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

      {/* 地图组件 */}
      <MapContainer
        currentLayer={state.currentLayer}
        showLegend={state.showLegend}
        fields={state.fields}
        selectedField={state.selectedField}
        onMapReady={handleMapReady}
        onLayerChange={handleLayerChange}
        onFieldSelect={handleFieldSelect}
      />

      {/* 选中地块信息 */}
      <SelectedFieldInfo
        selectedField={state.selectedField}
        onClose={handleCloseSelectedField}
      />

      {/* 地图信息面板 */}
      <MapInfoPanel
        currentLayer={state.currentLayer}
        fields={state.fields}
      />

      {/* 功能说明 */}
      <FeatureDescription />
    </div>
  );
}