'use client';

import { useReducer } from 'react';
import { MapLayer } from '@/lib/gisMapEngine';

// 地块数据接口
export interface Field {
  id: string;
  name: string;
  area: number;
  coordinates: { lng: number; lat: number }[];
  soilType: string;
  plantingMode: string;
  color: string;
}

// GIS状态接口
export interface GISMapState {
  mapEngine: any;
  currentLayer: MapLayer;
  selectedField: Field | null;
  showLegend: boolean;
  fields: Field[];
}

// Action类型
export type GISMapAction =
  | { type: 'SET_MAP_ENGINE'; payload: any }
  | { type: 'SET_CURRENT_LAYER'; payload: MapLayer }
  | { type: 'SET_SELECTED_FIELD'; payload: Field | null }
  | { type: 'TOGGLE_LEGEND' }
  | { type: 'SET_FIELDS'; payload: Field[] };

// 初始状态
const initialState: GISMapState = {
  mapEngine: null,
  currentLayer: 'satellite',
  selectedField: null,
  showLegend: true,
  fields: [
    {
      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',
    },
  ],
};

// Reducer函数
export function gisMapReducer(state: GISMapState, action: GISMapAction): GISMapState {
  switch (action.type) {
    case 'SET_MAP_ENGINE':
      return { ...state, mapEngine: action.payload };

    case 'SET_CURRENT_LAYER':
      return { ...state, currentLayer: action.payload };

    case 'SET_SELECTED_FIELD':
      return { ...state, selectedField: action.payload };

    case 'TOGGLE_LEGEND':
      return { ...state, showLegend: !state.showLegend };

    case 'SET_FIELDS':
      return { ...state, fields: action.payload };

    default:
      return state;
  }
}

// 导出初始状态和类型
export { initialState };
export type { GISMapAction, Field, GISMapState };