'use client';

import { useReducer } from 'react';

// 地块数据接口
export interface SpatialField {
  id: string;
  code: string;
  name: string;
  area: number;
  perimeter: number;
  centroid: { lat: number; lng: number };
  bounds: {
    north: number;
    south: number;
    east: number;
    west: number;
  };
  geometry: {
    type: 'Polygon';
    coordinates: number[][][]; // [[[lng, lat], ...], ...]
  };
  soilType: string;
  plantingMode: string;
  status: string;
  owner: string;
  createdAt: string;
}

// 空间查询状态接口
export interface SpatialQueryState {
  queryType: 'point-in-polygon' | 'polygon-intersect' | 'polygon-adjacent' | 'buffer';
  queryResult: any;
  queryGeometry: any;
  showGeometryDialog: boolean;
  bufferDistance: number;
  selectedPoint: { lat: number; lng: number } | null;
  queryPolygon: number[][] | null;
  selectedFields: string[];
  showMapPicker: boolean;
  mapPickerMode: 'point' | 'polygon';
  isQuerying: boolean;
  exportFormat: 'geojson' | 'kml' | 'csv';
  showExportDialog: boolean;
  activeTab: 'query' | 'analysis' | 'tools';
  calculationType: 'area' | 'perimeter' | 'centroid' | 'distance' | 'bounds';
  distanceStart: { lat: number; lng: number } | null;
  distanceEnd: { lat: number; lng: number } | null;
  analysisFields: string[];
}

// Action类型
export type SpatialQueryAction =
  | { type: 'SET_QUERY_TYPE'; payload: SpatialQueryState['queryType'] }
  | { type: 'SET_QUERY_RESULT'; payload: any }
  | { type: 'SET_QUERY_GEOMETRY'; payload: any }
  | { type: 'SET_SHOW_GEOMETRY_DIALOG'; payload: boolean }
  | { type: 'SET_BUFFER_DISTANCE'; payload: number }
  | { type: 'SET_SELECTED_POINT'; payload: { lat: number; lng: number } | null }
  | { type: 'SET_QUERY_POLYGON'; payload: number[][] | null }
  | { type: 'SET_SELECTED_FIELDS'; payload: string[] }
  | { type: 'SET_SHOW_MAP_PICKER'; payload: boolean }
  | { type: 'SET_MAP_PICKER_MODE'; payload: 'point' | 'polygon' }
  | { type: 'SET_IS_QUERYING'; payload: boolean }
  | { type: 'SET_EXPORT_FORMAT'; payload: 'geojson' | 'kml' | 'csv' }
  | { type: 'SET_SHOW_EXPORT_DIALOG'; payload: boolean }
  | { type: 'SET_ACTIVE_TAB'; payload: 'query' | 'analysis' | 'tools' }
  | { type: 'SET_CALCULATION_TYPE'; payload: 'area' | 'perimeter' | 'centroid' | 'distance' | 'bounds' }
  | { type: 'SET_DISTANCE_START'; payload: { lat: number; lng: number } | null }
  | { type: 'SET_DISTANCE_END'; payload: { lat: number; lng: number } | null }
  | { type: 'SET_ANALYSIS_FIELDS'; payload: string[] }
  | { type: 'RESET_QUERY' };

// 模拟地块数据
const mockFields: SpatialField[] = [
  {
    id: '1',
    code: 'TD001',
    name: '东区沙质土试验田',
    area: 85.5,
    perimeter: 1250,
    centroid: { lat: 39.9042, lng: 116.4074 },
    bounds: { north: 39.905, south: 39.903, east: 116.408, west: 116.406 },
    geometry: {
      type: 'Polygon',
      coordinates: [[
        [116.406, 39.903],
        [116.408, 39.903],
        [116.408, 39.905],
        [116.406, 39.905],
        [116.406, 39.903]
      ]]
    },
    soilType: 'sandy',
    plantingMode: 'conventional',
    status: 'active',
    owner: '张三',
    createdAt: '2024-01-15'
  },
  {
    id: '2',
    code: 'TD002',
    name: '西区黏质土示范区',
    area: 120.8,
    perimeter: 1680,
    centroid: { lat: 39.9048, lng: 116.4082 },
    bounds: { north: 39.906, south: 39.904, east: 116.409, west: 116.407 },
    geometry: {
      type: 'Polygon',
      coordinates: [[
        [116.407, 39.904],
        [116.409, 39.904],
        [116.409, 39.906],
        [116.407, 39.906],
        [116.407, 39.904]
      ]]
    },
    soilType: 'clay',
    plantingMode: 'organic',
    status: 'active',
    owner: '李四',
    createdAt: '2024-01-20'
  },
  {
    id: '3',
    code: 'TD003',
    name: '南区壤质土生产基地',
    area: 95.2,
    perimeter: 1420,
    centroid: { lat: 39.9038, lng: 116.4068 },
    bounds: { north: 39.904, south: 39.903, east: 116.407, west: 116.406 },
    geometry: {
      type: 'Polygon',
      coordinates: [[
        [116.406, 39.903],
        [116.407, 39.903],
        [116.407, 39.904],
        [116.406, 39.904],
        [116.406, 39.903]
      ]]
    },
    soilType: 'loamy',
    plantingMode: 'greenhouse',
    status: 'active',
    owner: '王五',
    createdAt: '2024-01-25'
  }
];

// 初始状态
const initialState: SpatialQueryState = {
  queryType: 'point-in-polygon',
  queryResult: null,
  queryGeometry: null,
  showGeometryDialog: false,
  bufferDistance: 100,
  selectedPoint: null,
  queryPolygon: null,
  selectedFields: [],
  showMapPicker: false,
  mapPickerMode: 'point',
  isQuerying: false,
  exportFormat: 'geojson',
  showExportDialog: false,
  activeTab: 'query',
  calculationType: 'area',
  distanceStart: null,
  distanceEnd: null,
  analysisFields: [],
};

// Reducer函数
export function spatialQueryReducer(state: SpatialQueryState, action: SpatialQueryAction): SpatialQueryState {
  switch (action.type) {
    case 'SET_QUERY_TYPE':
      return {
        ...state,
        queryType: action.payload,
        queryResult: null,
        selectedPoint: null,
        queryPolygon: null,
        selectedFields: []
      };

    case 'SET_QUERY_RESULT':
      return { ...state, queryResult: action.payload };

    case 'SET_QUERY_GEOMETRY':
      return { ...state, queryGeometry: action.payload };

    case 'SET_SHOW_GEOMETRY_DIALOG':
      return { ...state, showGeometryDialog: action.payload };

    case 'SET_BUFFER_DISTANCE':
      return { ...state, bufferDistance: action.payload };

    case 'SET_SELECTED_POINT':
      return { ...state, selectedPoint: action.payload };

    case 'SET_QUERY_POLYGON':
      return { ...state, queryPolygon: action.payload };

    case 'SET_SELECTED_FIELDS':
      return { ...state, selectedFields: action.payload };

    case 'SET_SHOW_MAP_PICKER':
      return { ...state, showMapPicker: action.payload };

    case 'SET_MAP_PICKER_MODE':
      return { ...state, mapPickerMode: action.payload };

    case 'SET_IS_QUERYING':
      return { ...state, isQuerying: action.payload };

    case 'SET_EXPORT_FORMAT':
      return { ...state, exportFormat: action.payload };

    case 'SET_SHOW_EXPORT_DIALOG':
      return { ...state, showExportDialog: action.payload };

    case 'SET_ACTIVE_TAB':
      return {
        ...state,
        activeTab: action.payload,
        queryResult: null
      };

    case 'SET_CALCULATION_TYPE':
      return { ...state, calculationType: action.payload };

    case 'SET_DISTANCE_START':
      return { ...state, distanceStart: action.payload };

    case 'SET_DISTANCE_END':
      return { ...state, distanceEnd: action.payload };

    case 'SET_ANALYSIS_FIELDS':
      return { ...state, analysisFields: action.payload };

    case 'RESET_QUERY':
      return {
        ...state,
        queryResult: null,
        selectedPoint: null,
        queryPolygon: null,
        selectedFields: [],
        queryGeometry: null,
        distanceStart: null,
        distanceEnd: null,
        analysisFields: []
      };

    default:
      return state;
  }
}

// 导出初始状态和类型
export { initialState, mockFields };
export type { SpatialQueryAction, SpatialField, SpatialQueryState };