'use client';

import { ReactNode } from 'react';

// 类型定义
export interface LandField {
  id: string;
  code: string;
  name: string;
  area: number;
  location: string;
  soilType: string;
  plantingMode: string;
  tags: string[];
  status: 'active' | 'inactive' | 'pending';
  description?: string;
  createdAt: string;
  updatedAt: string;
}

export interface LandTag {
  id: string;
  name: string;
  color: string;
  description?: string;
  createdAt: string;
}

export interface SoilType {
  id: string;
  key: string;
  name: string;
  color: string;
}

export interface PlantingMode {
  id: string;
  key: string;
  name: string;
  emoji: string;
}

export interface FilterCondition {
  soilTypes: string[];
  plantingModes: string[];
  tags: string[];
  minArea: string;
  maxArea: string;
  keyword: string;
}

export interface StatisticsResult {
  totalCount: number;
  totalArea: number;
  avgArea: number;
  maxArea: number;
  minArea: number;
  soilTypeDistribution: { name: string; count: number; area: number; color: string }[];
  plantingModeDistribution: { name: string; count: number; area: number; emoji: string }[];
  tagDistribution: { name: string; count: number; color: string }[];
}

export interface LandStatisticsState {
  fields: LandField[];
  tags: LandTag[];
  soilTypes: SoilType[];
  plantingModes: PlantingMode[];
  filters: FilterCondition;
  statistics: StatisticsResult | null;
  chartType: 'bar' | 'pie';
  loading: boolean;
}

// 初始状态
export const initialState: LandStatisticsState = {
  fields: [],
  tags: [],
  soilTypes: [],
  plantingModes: [],
  filters: {
    soilTypes: [],
    plantingModes: [],
    tags: [],
    minArea: '',
    maxArea: '',
    keyword: '',
  },
  statistics: null,
  chartType: 'bar',
  loading: false,
};

// Action 类型定义
export type LandStatisticsAction =
  | { type: 'SET_FIELDS'; payload: LandField[] }
  | { type: 'SET_TAGS'; payload: LandTag[] }
  | { type: 'SET_SOIL_TYPES'; payload: SoilType[] }
  | { type: 'SET_PLANTING_MODES'; payload: PlantingMode[] }
  | { type: 'UPDATE_FILTER'; payload: { key: keyof FilterCondition; value: any } }
  | { type: 'TOGGLE_ARRAY_FILTER'; payload: { key: 'soilTypes' | 'plantingModes' | 'tags'; value: string } }
  | { type: 'CLEAR_FILTERS' }
  | { type: 'SET_STATISTICS'; payload: StatisticsResult | null }
  | { type: 'SET_CHART_TYPE'; payload: 'bar' | 'pie' }
  | { type: 'SET_LOADING'; payload: boolean };

// Reducer 函数
export function LandStatisticsReducer(
  state: LandStatisticsState,
  action: LandStatisticsAction
): LandStatisticsState {
  switch (action.type) {
    case 'SET_FIELDS':
      return { ...state, fields: action.payload };

    case 'SET_TAGS':
      return { ...state, tags: action.payload };

    case 'SET_SOIL_TYPES':
      return { ...state, soilTypes: action.payload };

    case 'SET_PLANTING_MODES':
      return { ...state, plantingModes: action.payload };

    case 'UPDATE_FILTER':
      return {
        ...state,
        filters: {
          ...state.filters,
          [action.payload.key]: action.payload.value,
        },
      };

    case 'TOGGLE_ARRAY_FILTER':
      const { key, value } = action.payload;
      const currentArray = state.filters[key];
      const newArray = currentArray.includes(value)
        ? currentArray.filter(v => v !== value)
        : [...currentArray, value];

      return {
        ...state,
        filters: {
          ...state.filters,
          [key]: newArray,
        },
      };

    case 'CLEAR_FILTERS':
      return {
        ...state,
        filters: {
          soilTypes: [],
          plantingModes: [],
          tags: [],
          minArea: '',
          maxArea: '',
          keyword: '',
        },
        statistics: null,
      };

    case 'SET_STATISTICS':
      return { ...state, statistics: action.payload };

    case 'SET_CHART_TYPE':
      return { ...state, chartType: action.payload };

    case 'SET_LOADING':
      return { ...state, loading: action.payload };

    default:
      return state;
  }
}

// Context 类型定义
export interface LandStatisticsContextType {
  state: LandStatisticsState;
  dispatch: React.Dispatch<LandStatisticsAction>;
  loadData: (forceReload?: boolean) => void;
  executeQuery: () => void;
  exportData: () => void;
  handleFilterChange: (key: keyof FilterCondition, value: any) => void;
  handleToggleArrayFilter: (key: 'soilTypes' | 'plantingModes' | 'tags', value: string) => void;
  handleClearFilters: () => void;
  handleChartTypeChange: (type: 'bar' | 'pie') => void;
}