'use client';

import { toast } from 'sonner';

// 土壤采样点接口
export interface SoilLayer {
  depth: string; // 如 "0-20cm"
  deviceId?: string; // IoT设备ID，用于读取该层数据
  // 以下字段从设备读取，仅用于展示
  pH?: number;
  organicMatter?: number; // 有机质 g/kg
  nitrogen?: number; // 全氮 g/kg
  phosphorus?: number; // 有效磷 mg/kg
  potassium?: number; // 速效钾 mg/kg
  moisture?: number; // 含水量 %
}

export interface SamplePoint {
  id: string;
  code: string;
  fieldName: string;
  latitude: number;
  longitude: number;
  sampleDate: string;
  sampler: string;
  deviceId?: string; // IoT设备ID
  layers: SoilLayer[];
}

// IoT设备接口
export interface IoTDevice {
  id: string;
  code: string;
  name: string;
  type: string;
  status: 'online' | 'offline';
  // 实时监测数据
  data: {
    pH: number;
    organicMatter: number;
    nitrogen: number;
    phosphorus: number;
    potassium: number;
    moisture: number;
    lastUpdate: string;
  };
}

// 筛选条件接口
export interface SoilDataFilters {
  searchKeyword: string;
  selectedField: string;
  dateRange: {
    start: string;
    end: string;
  };
}

// 统计结果接口
export interface SoilDataStatistics {
  totalPoints: number;
  totalFields: number;
  totalLayers: number;
  averagePH: number;
  phDistribution: {
    strongAcidic: number; // 强酸性
    acidic: number; // 酸性
    neutral: number; // 中性
    alkaline: number; // 碱性
    strongAlkaline: number; // 强碱性
  };
  organicMatterDistribution: {
    veryLow: number; // 极低
    low: number; // 低
    medium: number; // 中等
    high: number; // 较高
    veryHigh: number; // 高
  };
}

// 状态接口
export interface SoilDataState {
  samplePoints: SamplePoint[];
  iotDevices: IoTDevice[];
  filters: SoilDataFilters;
  statistics: SoilDataStatistics | null;
  activeTab: string;
  showAddDialog: boolean;
  showEditDialog: boolean;
  showLayerDialog: boolean;
  showDeleteDialog: boolean;
  selectedPoint: SamplePoint | null;
  pointToDelete: string | null;
  newPoint: Partial<SamplePoint>;
  loading: boolean;
}

// Action类型
export type SoilDataAction =
  | { type: 'SET_SAMPLE_POINTS'; payload: SamplePoint[] }
  | { type: 'SET_IOT_DEVICES'; payload: IoTDevice[] }
  | { type: 'SET_FILTERS'; payload: Partial<SoilDataFilters> }
  | { type: 'SET_STATISTICS'; payload: SoilDataStatistics | null }
  | { type: 'SET_ACTIVE_TAB'; payload: string }
  | { type: 'SET_SHOW_ADD_DIALOG'; payload: boolean }
  | { type: 'SET_SHOW_EDIT_DIALOG'; payload: boolean }
  | { type: 'SET_SHOW_LAYER_DIALOG'; payload: boolean }
  | { type: 'SET_SHOW_DELETE_DIALOG'; payload: boolean }
  | { type: 'SET_SELECTED_POINT'; payload: SamplePoint | null }
  | { type: 'SET_POINT_TO_DELETE'; payload: string | null }
  | { type: 'SET_NEW_POINT'; payload: Partial<SamplePoint> }
  | { type: 'UPDATE_NEW_POINT'; payload: Partial<SamplePoint> }
  | { type: 'RESET_NEW_POINT' }
  | { type: 'SET_LOADING'; payload: boolean }
  | { type: 'ADD_SAMPLE_POINT'; payload: SamplePoint }
  | { type: 'UPDATE_SAMPLE_POINT'; payload: SamplePoint }
  | { type: 'DELETE_SAMPLE_POINT'; payload: string }
  | { type: 'LOAD_FROM_STORAGE' }
  | { type: 'SAVE_TO_STORAGE' };

// 初始状态
export const initialSoilDataState: SoilDataState = {
  samplePoints: [],
  iotDevices: [],
  filters: {
    searchKeyword: '',
    selectedField: 'all',
    dateRange: {
      start: '',
      end: ''
    }
  },
  statistics: null,
  activeTab: 'list',
  showAddDialog: false,
  showEditDialog: false,
  showLayerDialog: false,
  showDeleteDialog: false,
  selectedPoint: null,
  pointToDelete: null,
  newPoint: {
    code: '',
    fieldName: '',
    latitude: 0,
    longitude: 0,
    sampleDate: '',
    sampler: '',
    deviceId: '',
    layers: [
      { depth: '0-20cm', deviceId: '' },
      { depth: '20-40cm', deviceId: '' },
      { depth: '40-60cm', deviceId: '' },
    ]
  },
  loading: false
};

// 初始化测试数据
const initializeTestData = () => {
  const testDevices: IoTDevice[] = [
    {
      id: 'dev-1',
      code: 'IOT-SOIL-001',
      name: '土壤传感器001',
      type: '多参数土壤传感器',
      status: 'online',
      data: {
        pH: 6.8,
        organicMatter: 28.5,
        nitrogen: 1.2,
        phosphorus: 25.3,
        potassium: 180,
        moisture: 22.5,
        lastUpdate: '2024-10-18 14:30:00',
      },
    },
    {
      id: 'dev-2',
      code: 'IOT-SOIL-002',
      name: '土壤传感器002',
      type: '多参数土壤传感器',
      status: 'online',
      data: {
        pH: 7.2,
        organicMatter: 32.1,
        nitrogen: 1.5,
        phosphorus: 28.6,
        potassium: 195,
        moisture: 20.3,
        lastUpdate: '2024-10-18 14:28:00',
      },
    },
    {
      id: 'dev-3',
      code: 'IOT-SOIL-003',
      name: '土壤传感器003',
      type: '多参数土壤传感器',
      status: 'online',
      data: {
        pH: 5.8,
        organicMatter: 22.3,
        nitrogen: 0.9,
        phosphorus: 18.5,
        potassium: 152,
        moisture: 24.6,
        lastUpdate: '2024-10-18 14:25:00',
      },
    },
    {
      id: 'dev-4',
      code: 'IOT-SOIL-004',
      name: '土壤传感器004',
      type: '多参数土壤传感器',
      status: 'offline',
      data: {
        pH: 6.5,
        organicMatter: 18.2,
        nitrogen: 0.8,
        phosphorus: 18.5,
        potassium: 145,
        moisture: 25.8,
        lastUpdate: '2024-10-17 18:30:00',
      },
    },
  ];

  const testPoints: SamplePoint[] = [
    {
      id: 'sp-1',
      code: 'SP001',
      fieldName: '东区1号地',
      latitude: 39.9042,
      longitude: 116.4074,
      sampleDate: '2024-10-15',
      sampler: '张三',
      deviceId: 'dev-1',
      layers: [
        { depth: '0-20cm', deviceId: 'dev-1', pH: 6.8, organicMatter: 28.5, nitrogen: 1.2, phosphorus: 25.3, potassium: 180, moisture: 22.5 },
        { depth: '20-40cm', deviceId: 'dev-1', pH: 6.5, organicMatter: 18.2, nitrogen: 0.8, phosphorus: 18.5, potassium: 145, moisture: 25.8 },
        { depth: '40-60cm', deviceId: 'dev-1', pH: 6.3, organicMatter: 12.5, nitrogen: 0.5, phosphorus: 12.3, potassium: 98, moisture: 28.2 },
      ],
    },
    {
      id: 'sp-2',
      code: 'SP002',
      fieldName: '东区1号地',
      latitude: 39.9052,
      longitude: 116.4084,
      sampleDate: '2024-10-15',
      sampler: '张三',
      deviceId: 'dev-2',
      layers: [
        { depth: '0-20cm', deviceId: 'dev-2', pH: 7.2, organicMatter: 32.1, nitrogen: 1.5, phosphorus: 28.6, potassium: 195, moisture: 20.3 },
        { depth: '20-40cm', deviceId: 'dev-2', pH: 6.8, organicMatter: 22.3, nitrogen: 1.0, phosphorus: 21.2, potassium: 158, moisture: 23.5 },
      ],
    },
    {
      id: 'sp-3',
      code: 'SP003',
      fieldName: '西区2号地',
      latitude: 39.9032,
      longitude: 116.4064,
      sampleDate: '2024-10-14',
      sampler: '李四',
      deviceId: 'dev-3',
      layers: [
        { depth: '0-20cm', deviceId: 'dev-3', pH: 5.8, organicMatter: 22.3, nitrogen: 0.9, phosphorus: 18.5, potassium: 152, moisture: 24.6 },
        { depth: '20-40cm', deviceId: 'dev-3', pH: 5.5, organicMatter: 15.8, nitrogen: 0.6, phosphorus: 14.2, potassium: 125, moisture: 26.8 },
        { depth: '40-60cm', deviceId: 'dev-3', pH: 5.3, organicMatter: 10.2, nitrogen: 0.4, phosphorus: 9.8, potassium: 88, moisture: 29.1 },
      ],
    },
  ];

  return { devices: testDevices, points: testPoints };
};

// 计算统计数据
const calculateStatistics = (points: SamplePoint[]): SoilDataStatistics => {
  const totalPoints = points.length;
  const uniqueFields = new Set(points.map(p => p.fieldName));
  const totalFields = uniqueFields.size;
  const totalLayers = points.reduce((sum, p) => sum + p.layers.length, 0);

  // 计算平均pH值
  const phValues = points.flatMap(p => p.layers.map(l => l.pH || 0));
  const averagePH = phValues.length > 0 ? phValues.reduce((sum, ph) => sum + ph, 0) / phValues.length : 0;

  // pH分布统计
  const phDistribution = phValues.reduce((acc, ph) => {
    if (ph < 5.5) acc.strongAcidic++;
    else if (ph < 6.5) acc.acidic++;
    else if (ph < 7.5) acc.neutral++;
    else if (ph < 8.5) acc.alkaline++;
    else acc.strongAlkaline++;
    return acc;
  }, { strongAcidic: 0, acidic: 0, neutral: 0, alkaline: 0, strongAlkaline: 0 });

  // 有机质分布统计
  const organicMatterValues = points.flatMap(p => p.layers.map(l => l.organicMatter || 0));
  const organicMatterDistribution = organicMatterValues.reduce((acc, om) => {
    if (om < 10) acc.veryLow++;
    else if (om < 20) acc.low++;
    else if (om < 30) acc.medium++;
    else if (om < 40) acc.high++;
    else acc.veryHigh++;
    return acc;
  }, { veryLow: 0, low: 0, medium: 0, high: 0, veryHigh: 0 });

  return {
    totalPoints,
    totalFields,
    totalLayers,
    averagePH,
    phDistribution,
    organicMatterDistribution
  };
};

// Reducer函数
export function soilDataReducer(state: SoilDataState, action: SoilDataAction): SoilDataState {
  switch (action.type) {
    case 'SET_SAMPLE_POINTS':
      return {
        ...state,
        samplePoints: action.payload,
        statistics: calculateStatistics(action.payload)
      };

    case 'SET_IOT_DEVICES':
      return { ...state, iotDevices: action.payload };

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

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

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

    case 'SET_SHOW_ADD_DIALOG':
      if (action.payload) {
        return {
          ...state,
          showAddDialog: action.payload,
          newPoint: {
            code: '',
            fieldName: '',
            latitude: 0,
            longitude: 0,
            sampleDate: '',
            sampler: '',
            deviceId: '',
            layers: [
              { depth: '0-20cm', deviceId: '' },
              { depth: '20-40cm', deviceId: '' },
              { depth: '40-60cm', deviceId: '' },
            ]
          }
        };
      }
      return { ...state, showAddDialog: action.payload };

    case 'SET_SHOW_EDIT_DIALOG':
      return { ...state, showEditDialog: action.payload };

    case 'SET_SHOW_LAYER_DIALOG':
      return { ...state, showLayerDialog: action.payload };

    case 'SET_SHOW_DELETE_DIALOG':
      return { ...state, showDeleteDialog: action.payload };

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

    case 'SET_POINT_TO_DELETE':
      return { ...state, pointToDelete: action.payload };

    case 'SET_NEW_POINT':
      return { ...state, newPoint: action.payload };

    case 'UPDATE_NEW_POINT':
      return {
        ...state,
        newPoint: { ...state.newPoint, ...action.payload }
      };

    case 'RESET_NEW_POINT':
      return {
        ...state,
        newPoint: {
          code: '',
          fieldName: '',
          latitude: 0,
          longitude: 0,
          sampleDate: '',
          sampler: '',
          deviceId: '',
          layers: [
            { depth: '0-20cm', deviceId: '' },
            { depth: '20-40cm', deviceId: '' },
            { depth: '40-60cm', deviceId: '' },
          ]
        }
      };

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

    case 'ADD_SAMPLE_POINT':
      const updatedPoints = [...state.samplePoints, action.payload];
      toast.success('采样点添加成功！');
      return {
        ...state,
        samplePoints: updatedPoints,
        statistics: calculateStatistics(updatedPoints)
      };

    case 'UPDATE_SAMPLE_POINT':
      const updatedPointsList = state.samplePoints.map(point =>
        point.id === action.payload.id ? action.payload : point
      );
      toast.success('采样点更新成功！');
      return {
        ...state,
        samplePoints: updatedPointsList,
        statistics: calculateStatistics(updatedPointsList)
      };

    case 'DELETE_SAMPLE_POINT':
      const filteredPoints = state.samplePoints.filter(p => p.id !== action.payload);
      toast.success('采样点已删除');
      return {
        ...state,
        samplePoints: filteredPoints,
        statistics: calculateStatistics(filteredPoints)
      };

    case 'LOAD_FROM_STORAGE':
      try {
        const stored = localStorage.getItem('soilData');
        if (stored) {
          const parsedData = JSON.parse(stored);
          return {
            ...state,
            samplePoints: parsedData.samplePoints || [],
            statistics: calculateStatistics(parsedData.samplePoints || [])
          };
        } else {
          // 首次加载，初始化测试数据
          const testData = initializeTestData();
          localStorage.setItem('soilData', JSON.stringify({
            samplePoints: testData.points
          }));
          return {
            ...state,
            samplePoints: testData.points,
            iotDevices: testData.devices,
            statistics: calculateStatistics(testData.points)
          };
        }
      } catch (error) {
        console.error('Failed to load soil data from storage:', error);
        return state;
      }

    case 'SAVE_TO_STORAGE':
      try {
        localStorage.setItem('soilData', JSON.stringify({
          samplePoints: state.samplePoints
        }));
      } catch (error) {
        console.error('Failed to save soil data to storage:', error);
      }
      return state;

    default:
      return state;
  }
}

// 工具函数
export const getPHLevel = (pH: number) => {
  if (pH < 5.5) return { label: '强酸性', color: 'bg-red-500' };
  if (pH < 6.5) return { label: '酸性', color: 'bg-orange-500' };
  if (pH < 7.5) return { label: '中性', color: 'bg-green-500' };
  if (pH < 8.5) return { label: '碱性', color: 'bg-blue-500' };
  return { label: '强碱性', color: 'bg-purple-500' };
};

export const getOrganicMatterLevel = (om: number) => {
  if (om < 10) return { label: '极低', color: 'text-red-600' };
  if (om < 20) return { label: '低', color: 'text-orange-600' };
  if (om < 30) return { label: '中等', color: 'text-yellow-600' };
  if (om < 40) return { label: '较高', color: 'text-green-600' };
  return { label: '高', color: 'text-blue-600' };
};