'use client';

// 空间分析数据类型定义
export interface LandBlock {
  id: string;
  name: string;
  area: number;
  location: {
    lat: number;
    lng: number;
  };
  soilType: string;
  currentCrop?: string;
  elevation?: number;
  slope?: number;
  irrigation?: string;
  pH?: number;
  organicMatter?: number;
  nitrogen?: number;
  phosphorus?: number;
  potassium?: number;
  suitabilityIndex?: number; // 适宜性指数
  lastAnalyzed?: string; // 最后分析时间
  analysisStatus?: 'pending' | 'analyzing' | 'completed' | 'failed'; // 分析状态
}

export interface CropInfo {
  id: string;
  name: string;
  category: string;
  growthCycle: number;
  soilRequirements: {
    pH: { min: number; max: number };
    organicMatter: { min: number };
    nitrogen: { min: number };
    phosphorus: { min: number };
    potassium: { min: number };
  };
  climateRequirements: {
    temperature: { min: number; max: number };
    rainfall: { min: number; max: number };
    sunlight: { min: number };
  };
  economicValue: number;
  riskLevel: 'low' | 'medium' | 'high';
  suitableRegions: string[];
}

export interface EvaluationFactor {
  id: string;
  name: string;
  weight: number;
  enabled: boolean;
  category: 'soil' | 'climate' | 'topography' | 'infrastructure';
  description: string;
}

export interface AnalysisResult {
  blockId: string;
  blockName: string;
  overallScore: number;
  soilScore: number;
  climateScore: number;
  topographyScore: number;
  infrastructureScore: number;
  recommendedCrops: CropRecommendation[];
  riskFactors: string[];
  improvementSuggestions: string[];
  estimatedYield?: number;
  economicReturn?: number;
}

export interface CropRecommendation {
  crop: CropInfo;
  suitabilityScore: number;
  matchPercentage: number;
  advantages: string[];
  disadvantages: string[];
  managementNotes: string[];
}

export interface WeightConfig {
  soil: number;
  climate: number;
  topography: number;
  infrastructure: number;
}

export interface AnalysisReport {
  id: string;
  title: string;
  createdAt: string;
  landBlocks: LandBlock[];
  results: AnalysisResult[];
  factors: EvaluationFactor[];
  weightConfig: WeightConfig;
  summary: {
    totalBlocks: number;
    averageScore: number;
    topRecommendedCrops: Array<{ crop: string; frequency: number; avgScore: number }>;
    riskDistribution: { low: number; medium: number; high: number };
  };
}

// 批量分析任务状态
export interface BatchAnalysisTask {
  id: string;
  name: string;
  status: 'pending' | 'running' | 'completed' | 'failed' | 'paused';
  createdAt: string;
  startedAt?: string;
  completedAt?: string;
  totalBlocks: number;
  processedBlocks: number;
  successCount: number;
  failedCount: number;
  selectedBlockIds: string[];
  weightConfig: WeightConfig;
  factorIds: string[];
  progress: number;
  currentProcessingBlock?: string;
  errorMessage?: string;
}

// 状态管理
export interface SpatialAnalysisState {
  // 地块数据
  landBlocks: LandBlock[];
  selectedBlocks: string[];

  // 评价因子
  factors: EvaluationFactor[];
  weightConfig: WeightConfig;

  // 作物数据库
  cropDatabase: CropInfo[];
  selectedCrops: string[];

  // 分析结果
  analysisResults: AnalysisResult[];
  currentReport: AnalysisReport | null;

  // 批量分析任务
  batchTasks: BatchAnalysisTask[];
  currentTask: BatchAnalysisTask | null;
  isBatchAnalyzing: boolean;

  // UI状态
  activeTab: string;
  isAnalyzing: boolean;
  showWeightDialog: boolean;
  showFactorDialog: boolean;
  showCompareDialog: boolean;

  // 筛选条件
  filters: {
    scoreRange: [number, number];
    soilTypes: string[];
    riskLevels: string[];
    cropCategories: string[];
  };

  // 图表数据
  chartData: {
    scoreDistribution: Array<{ range: string; count: number }>;
    factorPerformance: Array<{ factor: string; score: number; weight: number }>;
    cropComparison: Array<{ crop: string; suitability: number; economic: number; risk: string }>;
  };
}

// 动作类型
export type SpatialAnalysisAction =
  | { type: 'SET_LAND_BLOCKS'; payload: LandBlock[] }
  | { type: 'ADD_LAND_BLOCK'; payload: LandBlock }
  | { type: 'UPDATE_LAND_BLOCK'; payload: { id: string; updates: Partial<LandBlock> } }
  | { type: 'DELETE_LAND_BLOCK'; payload: string }
  | { type: 'SET_SELECTED_BLOCKS'; payload: string[] }
  | { type: 'TOGGLE_BLOCK_SELECTION'; payload: string }

  | { type: 'SET_FACTORS'; payload: EvaluationFactor[] }
  | { type: 'UPDATE_FACTOR_WEIGHT'; payload: { id: string; weight: number } }
  | { type: 'TOGGLE_FACTOR'; payload: string }
  | { type: 'SET_WEIGHT_CONFIG'; payload: WeightConfig }

  | { type: 'SET_CROP_DATABASE'; payload: CropInfo[] }
  | { type: 'SET_SELECTED_CROPS'; payload: string[] }

  | { type: 'SET_ANALYSIS_RESULTS'; payload: AnalysisResult[] }
  | { type: 'ADD_ANALYSIS_RESULT'; payload: AnalysisResult }
  | { type: 'SET_CURRENT_REPORT'; payload: AnalysisReport | null }

  | { type: 'SET_ACTIVE_TAB'; payload: string }
  | { type: 'SET_ANALYZING'; payload: boolean }
  | { type: 'TOGGLE_WEIGHT_DIALOG' }
  | { type: 'TOGGLE_FACTOR_DIALOG' }
  | { type: 'TOGGLE_COMPARE_DIALOG' }

  | { type: 'SET_FILTERS'; payload: Partial<SpatialAnalysisState['filters']> }
  | { type: 'RESET_FILTERS' }

  | { type: 'SET_CHART_DATA'; payload: Partial<SpatialAnalysisState['chartData']> }

  | { type: 'RUN_ANALYSIS'; payload: { blockIds?: string[] } }
  | { type: 'GENERATE_REPORT'; payload: { title: string } }

  // 批量分析相关动作
  | { type: 'START_BATCH_ANALYSIS'; payload: { name: string; blockIds: string[] } }
  | { type: 'UPDATE_BATCH_TASK'; payload: { taskId: string; updates: Partial<BatchAnalysisTask> } }
  | { type: 'SET_CURRENT_TASK'; payload: BatchAnalysisTask | null }
  | { type: 'COMPLETE_BATCH_ANALYSIS'; payload: { taskId: string; results: AnalysisResult[] } }
  | { type: 'PAUSE_BATCH_ANALYSIS'; payload: { taskId: string } }
  | { type: 'RESUME_BATCH_ANALYSIS'; payload: { taskId: string } }
  | { type: 'CANCEL_BATCH_ANALYSIS'; payload: { taskId: string } }
  | { type: 'UPDATE_BLOCK_ANALYSIS_STATUS'; payload: { blockId: string; status: LandBlock['analysisStatus']; suitabilityIndex?: number } }

  | { type: 'LOAD_FROM_STORAGE' }
  | { type: 'SAVE_TO_STORAGE' }
  | { type: 'RESET_STATE' };

// 默认评价因子
const defaultFactors: EvaluationFactor[] = [
  {
    id: 'soil_ph',
    name: '土壤pH值',
    weight: 0.15,
    enabled: true,
    category: 'soil',
    description: '土壤酸碱度对作物生长的影响'
  },
  {
    id: 'soil_organic_matter',
    name: '有机质含量',
    weight: 0.12,
    enabled: true,
    category: 'soil',
    description: '土壤肥力的重要指标'
  },
  {
    id: 'soil_nutrients',
    name: '土壤养分',
    weight: 0.18,
    enabled: true,
    category: 'soil',
    description: '氮磷钾等营养元素含量'
  },
  {
    id: 'soil_texture',
    name: '土壤质地',
    weight: 0.10,
    enabled: true,
    category: 'soil',
    description: '土壤物理结构和透气性'
  },
  {
    id: 'temperature',
    name: '温度条件',
    weight: 0.15,
    enabled: true,
    category: 'climate',
    description: '积温和温度适宜性'
  },
  {
    id: 'rainfall',
    name: '降水条件',
    weight: 0.12,
    enabled: true,
    category: 'climate',
    description: '降雨量及其分布'
  },
  {
    id: 'sunlight',
    name: '光照条件',
    weight: 0.10,
    enabled: true,
    category: 'climate',
    description: '日照时数和光照强度'
  },
  {
    id: 'elevation',
    name: '海拔高度',
    weight: 0.08,
    enabled: true,
    category: 'topography',
    description: '海拔对气候和作物的影响'
  },
  {
    id: 'slope',
    name: '坡度坡向',
    weight: 0.06,
    enabled: true,
    category: 'topography',
    description: '地形对水土保持的影响'
  },
  {
    id: 'irrigation',
    name: '灌溉条件',
    weight: 0.12,
    enabled: true,
    category: 'infrastructure',
    description: '水利设施和灌溉保障'
  },
  {
    id: 'accessibility',
    name: '交通便利性',
    weight: 0.05,
    enabled: true,
    category: 'infrastructure',
    description: '道路和运输条件'
  }
];

// 默认权重配置
const defaultWeightConfig: WeightConfig = {
  soil: 0.35,
  climate: 0.30,
  topography: 0.20,
  infrastructure: 0.15
};

// 初始状态
export const initialSpatialAnalysisState: SpatialAnalysisState = {
  landBlocks: [],
  selectedBlocks: [],
  factors: defaultFactors,
  weightConfig: defaultWeightConfig,
  cropDatabase: [],
  selectedCrops: [],
  analysisResults: [],
  currentReport: null,
  batchTasks: [],
  currentTask: null,
  isBatchAnalyzing: false,
  activeTab: 'overview',
  isAnalyzing: false,
  showWeightDialog: false,
  showFactorDialog: false,
  showCompareDialog: false,
  filters: {
    scoreRange: [0, 100],
    soilTypes: [],
    riskLevels: [],
    cropCategories: []
  },
  chartData: {
    scoreDistribution: [],
    factorPerformance: [],
    cropComparison: []
  }
};

// Reducer
export function spatialAnalysisReducer(
  state: SpatialAnalysisState,
  action: SpatialAnalysisAction
): SpatialAnalysisState {
  switch (action.type) {
    case 'SET_LAND_BLOCKS':
      return { ...state, landBlocks: action.payload };

    case 'ADD_LAND_BLOCK':
      return { ...state, landBlocks: [...state.landBlocks, action.payload] };

    case 'UPDATE_LAND_BLOCK':
      return {
        ...state,
        landBlocks: state.landBlocks.map(block =>
          block.id === action.payload.id
            ? { ...block, ...action.payload.updates }
            : block
        )
      };

    case 'DELETE_LAND_BLOCK':
      return {
        ...state,
        landBlocks: state.landBlocks.filter(block => block.id !== action.payload),
        selectedBlocks: state.selectedBlocks.filter(id => id !== action.payload)
      };

    case 'SET_SELECTED_BLOCKS':
      return { ...state, selectedBlocks: action.payload };

    case 'TOGGLE_BLOCK_SELECTION':
      const isSelected = state.selectedBlocks.includes(action.payload);
      return {
        ...state,
        selectedBlocks: isSelected
          ? state.selectedBlocks.filter(id => id !== action.payload)
          : [...state.selectedBlocks, action.payload]
      };

    case 'SET_FACTORS':
      return { ...state, factors: action.payload };

    case 'UPDATE_FACTOR_WEIGHT':
      return {
        ...state,
        factors: state.factors.map(factor =>
          factor.id === action.payload.id
            ? { ...factor, weight: action.payload.weight }
            : factor
        )
      };

    case 'TOGGLE_FACTOR':
      return {
        ...state,
        factors: state.factors.map(factor =>
          factor.id === action.payload
            ? { ...factor, enabled: !factor.enabled }
            : factor
        )
      };

    case 'SET_WEIGHT_CONFIG':
      return { ...state, weightConfig: action.payload };

    case 'SET_CROP_DATABASE':
      return { ...state, cropDatabase: action.payload };

    case 'SET_SELECTED_CROPS':
      return { ...state, selectedCrops: action.payload };

    case 'SET_ANALYSIS_RESULTS':
      return { ...state, analysisResults: action.payload };

    case 'ADD_ANALYSIS_RESULT':
      return { ...state, analysisResults: [...state.analysisResults, action.payload] };

    case 'SET_CURRENT_REPORT':
      return { ...state, currentReport: action.payload };

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

    case 'SET_ANALYZING':
      return { ...state, isAnalyzing: action.payload };

    case 'TOGGLE_WEIGHT_DIALOG':
      return { ...state, showWeightDialog: !state.showWeightDialog };

    case 'TOGGLE_FACTOR_DIALOG':
      return { ...state, showFactorDialog: !state.showFactorDialog };

    case 'TOGGLE_COMPARE_DIALOG':
      return { ...state, showCompareDialog: !state.showCompareDialog };

    case 'SET_FILTERS':
      return {
        ...state,
        filters: { ...state.filters, ...action.payload }
      };

    case 'RESET_FILTERS':
      return {
        ...state,
        filters: {
          scoreRange: [0, 100],
          soilTypes: [],
          riskLevels: [],
          cropCategories: []
        }
      };

    case 'SET_CHART_DATA':
      return {
        ...state,
        chartData: { ...state.chartData, ...action.payload }
      };

    case 'RUN_ANALYSIS':
      // 这里会触发分析逻辑，实际实现在组件中处理
      return { ...state, isAnalyzing: true };

    case 'GENERATE_REPORT':
      // 报告生成逻辑在组件中处理
      return state;

    // 批量分析相关处理
    case 'START_BATCH_ANALYSIS':
      const newTask: BatchAnalysisTask = {
        id: Date.now().toString(),
        name: action.payload.name,
        status: 'pending',
        createdAt: new Date().toLocaleString('zh-CN'),
        totalBlocks: action.payload.blockIds.length,
        processedBlocks: 0,
        successCount: 0,
        failedCount: 0,
        selectedBlockIds: action.payload.blockIds,
        weightConfig: state.weightConfig,
        factorIds: state.factors.filter(f => f.enabled).map(f => f.id),
        progress: 0
      };
      return {
        ...state,
        batchTasks: [...state.batchTasks, newTask],
        currentTask: newTask,
        isBatchAnalyzing: true
      };

    case 'UPDATE_BATCH_TASK':
      return {
        ...state,
        batchTasks: state.batchTasks.map(task =>
          task.id === action.payload.taskId
            ? { ...task, ...action.payload.updates }
            : task
        ),
        currentTask: state.currentTask?.id === action.payload.taskId
          ? { ...state.currentTask, ...action.payload.updates }
          : state.currentTask
      };

    case 'SET_CURRENT_TASK':
      return {
        ...state,
        currentTask: action.payload
      };

    case 'COMPLETE_BATCH_ANALYSIS':
      return {
        ...state,
        batchTasks: state.batchTasks.map(task =>
          task.id === action.payload.taskId
            ? {
                ...task,
                status: 'completed',
                completedAt: new Date().toLocaleString('zh-CN'),
                progress: 100
              }
            : task
        ),
        analysisResults: action.payload.results,
        isBatchAnalyzing: false
      };

    case 'PAUSE_BATCH_ANALYSIS':
      return {
        ...state,
        batchTasks: state.batchTasks.map(task =>
          task.id === action.payload.taskId
            ? { ...task, status: 'paused' }
            : task
        ),
        isBatchAnalyzing: false
      };

    case 'RESUME_BATCH_ANALYSIS':
      return {
        ...state,
        batchTasks: state.batchTasks.map(task =>
          task.id === action.payload.taskId
            ? { ...task, status: 'running' }
            : task
        ),
        isBatchAnalyzing: true
      };

    case 'CANCEL_BATCH_ANALYSIS':
      return {
        ...state,
        batchTasks: state.batchTasks.map(task =>
          task.id === action.payload.taskId
            ? { ...task, status: 'failed', errorMessage: '用户取消分析' }
            : task
        ),
        currentTask: null,
        isBatchAnalyzing: false
      };

    case 'UPDATE_BLOCK_ANALYSIS_STATUS':
      return {
        ...state,
        landBlocks: state.landBlocks.map(block =>
          block.id === action.payload.blockId
            ? {
                ...block,
                analysisStatus: action.payload.status,
                ...(action.payload.suitabilityIndex && { suitabilityIndex: action.payload.suitabilityIndex }),
                lastAnalyzed: action.payload.status === 'completed' ? new Date().toLocaleString('zh-CN') : block.lastAnalyzed
              }
            : block
        )
      };

    case 'LOAD_FROM_STORAGE':
      try {
        const savedData = localStorage.getItem('spatial-analysis-data');
        if (savedData) {
          const parsed = JSON.parse(savedData);
          return { ...state, ...parsed };
        }
      } catch (error) {
        console.error('Failed to load spatial analysis data:', error);
      }
      return state;

    case 'SAVE_TO_STORAGE':
      try {
        const dataToSave = {
          landBlocks: state.landBlocks,
          selectedBlocks: state.selectedBlocks,
          factors: state.factors,
          weightConfig: state.weightConfig,
          analysisResults: state.analysisResults,
          filters: state.filters
        };
        localStorage.setItem('spatial-analysis-data', JSON.stringify(dataToSave));
      } catch (error) {
        console.error('Failed to save spatial analysis data:', error);
      }
      return state;

    case 'RESET_STATE':
      return initialSpatialAnalysisState;

    default:
      return state;
  }
}