'use client';

import { toast } from 'sonner';

// 气象数据接口
export interface WeatherData {
  time: string;
  temperature: number;
  humidity: number;
  windSpeed: number;
  rainfall: number;
  sunlight: number;
  pressure: number;
}

// 天气预警接口
export interface WeatherAlert {
  id: string;
  type: '低温冻害' | '大风' | '暴雨' | '高温';
  level: '预警' | '警报' | '紧急';
  message: string;
  time: string;
  affectedFields: string[];
}

// 天气预报接口
export interface WeatherForecast {
  day: string;
  weather: string;
  tempRange: string;
  icon: string;
  description?: string;
}

// 气象站配置接口
export interface WeatherStationConfig {
  enabled: boolean;
  apiEndpoint: string;
  apiKey: string;
  latitude: number;
  longitude: number;
  stationName: string;
  updateInterval: number; // 分钟
}

// 筛选条件接口
export interface WeatherFilters {
  selectedField: string;
  timeRange: '24h' | '7d' | '30d';
}

// 统计分析结果接口
export interface WeatherStatistics {
  temperature: {
    max: number;
    min: number;
    avg: number;
    range: number;
  };
  precipitation: {
    total: number;
    maxHourly: number;
    timeRange: string;
    intensity: string;
  };
  wind: {
    maxSpeed: number;
    avgSpeed: number;
    level: string;
    direction: string;
  };
  other: {
    avgHumidity: number;
    totalSunlight: number;
    avgPressure: number;
  };
}

// 状态接口
export interface WeatherDataState {
  weatherData: WeatherData[];
  weatherAlerts: WeatherAlert[];
  weatherForecast: WeatherForecast[];
  weatherStation: WeatherStationConfig;
  filters: WeatherFilters;
  statistics: WeatherStatistics | null;
  activeTab: string;
  acknowledgedAlerts: string[];
  isRefreshing: boolean;
  lastUpdateTime: string;
  loading: boolean;
}

// Action类型
export type WeatherDataAction =
  | { type: 'SET_WEATHER_DATA'; payload: WeatherData[] }
  | { type: 'SET_WEATHER_ALERTS'; payload: WeatherAlert[] }
  | { type: 'SET_WEATHER_FORECAST'; payload: WeatherForecast[] }
  | { type: 'SET_WEATHER_STATION'; payload: WeatherStationConfig }
  | { type: 'SET_FILTERS'; payload: Partial<WeatherFilters> }
  | { type: 'SET_STATISTICS'; payload: WeatherStatistics | null }
  | { type: 'SET_ACTIVE_TAB'; payload: string }
  | { type: 'ACKNOWLEDGE_ALERT'; payload: string }
  | { type: 'ACKNOWLEDGE_ALL_ALERTS' }
  | { type: 'SET_REFRESHING'; payload: boolean }
  | { type: 'SET_LAST_UPDATE_TIME'; payload: string }
  | { type: 'SET_LOADING'; payload: boolean }
  | { type: 'ADD_WEATHER_ALERT'; payload: WeatherAlert }
  | { type: 'REMOVE_WEATHER_ALERT'; payload: string }
  | { type: 'UPDATE_WEATHER_DATA'; payload: WeatherData[] }
  | { type: 'LOAD_FROM_STORAGE' }
  | { type: 'SAVE_TO_STORAGE' };

// 初始状态
export const initialWeatherDataState: WeatherDataState = {
  weatherData: [],
  weatherAlerts: [],
  weatherForecast: [],
  weatherStation: {
    enabled: true,
    apiEndpoint: 'https://api.weather.example.com/data',
    apiKey: 'YOUR_API_KEY_HERE',
    latitude: 39.9042,
    longitude: 116.4074,
    stationName: '智慧农场气象站',
    updateInterval: 15,
  },
  filters: {
    selectedField: 'field-1',
    timeRange: '24h',
  },
  statistics: null,
  activeTab: 'charts',
  acknowledgedAlerts: [],
  isRefreshing: false,
  lastUpdateTime: '',
  loading: false,
};

// 生成测试数据
const generateTestData = (timeRange: '24h' | '7d' | '30d'): WeatherData[] => {
  if (timeRange === '24h') {
    // 24小时数据 - 每3小时一个数据点
    return [
      { time: '00:00', temperature: 12, humidity: 75, windSpeed: 2.5, rainfall: 0, sunlight: 0, pressure: 1013 },
      { time: '03:00', temperature: 10, humidity: 80, windSpeed: 2.0, rainfall: 0, sunlight: 0, pressure: 1012 },
      { time: '06:00', temperature: 9, humidity: 85, windSpeed: 1.8, rainfall: 0, sunlight: 50, pressure: 1012 },
      { time: '09:00', temperature: 15, humidity: 70, windSpeed: 3.2, rainfall: 0, sunlight: 450, pressure: 1013 },
      { time: '12:00', temperature: 22, humidity: 55, windSpeed: 4.5, rainfall: 0, sunlight: 850, pressure: 1014 },
      { time: '15:00', temperature: 25, humidity: 48, windSpeed: 5.2, rainfall: 0, sunlight: 680, pressure: 1013 },
      { time: '18:00', temperature: 20, humidity: 60, windSpeed: 3.8, rainfall: 2, sunlight: 150, pressure: 1012 },
      { time: '21:00', temperature: 16, humidity: 68, windSpeed: 3.0, rainfall: 5, sunlight: 0, pressure: 1011 },
    ];
  } else if (timeRange === '7d') {
    // 7天数据 - 每天一个数据点
    return [
      { time: '10-12', temperature: 18, humidity: 68, windSpeed: 3.2, rainfall: 2, sunlight: 520, pressure: 1012 },
      { time: '10-13', temperature: 20, humidity: 62, windSpeed: 4.1, rainfall: 0, sunlight: 680, pressure: 1013 },
      { time: '10-14', temperature: 22, humidity: 58, windSpeed: 3.8, rainfall: 5, sunlight: 720, pressure: 1014 },
      { time: '10-15', temperature: 19, humidity: 72, windSpeed: 5.5, rainfall: 12, sunlight: 450, pressure: 1011 },
      { time: '10-16', temperature: 16, humidity: 78, windSpeed: 4.8, rainfall: 8, sunlight: 380, pressure: 1010 },
      { time: '10-17', temperature: 21, humidity: 65, windSpeed: 3.5, rainfall: 0, sunlight: 750, pressure: 1013 },
      { time: '10-18', temperature: 23, humidity: 60, windSpeed: 3.0, rainfall: 0, sunlight: 800, pressure: 1015 },
    ];
  } else {
    // 30天数据 - 每5天一个数据点
    return [
      { time: '09-19', temperature: 15, humidity: 70, windSpeed: 3.5, rainfall: 15, sunlight: 480, pressure: 1011 },
      { time: '09-24', temperature: 17, humidity: 68, windSpeed: 4.0, rainfall: 8, sunlight: 550, pressure: 1012 },
      { time: '09-29', temperature: 19, humidity: 65, windSpeed: 3.8, rainfall: 5, sunlight: 620, pressure: 1013 },
      { time: '10-04', temperature: 21, humidity: 62, windSpeed: 4.2, rainfall: 3, sunlight: 680, pressure: 1014 },
      { time: '10-09', temperature: 20, humidity: 66, windSpeed: 3.9, rainfall: 10, sunlight: 600, pressure: 1012 },
      { time: '10-14', temperature: 22, humidity: 58, windSpeed: 3.5, rainfall: 2, sunlight: 720, pressure: 1015 },
      { time: '10-18', temperature: 23, humidity: 60, windSpeed: 3.0, rainfall: 0, sunlight: 800, pressure: 1015 },
    ];
  }
};

// 生成测试预警数据
const generateTestAlerts = (): WeatherAlert[] => [
  {
    id: 'alert-1',
    type: '大风',
    level: '预警',
    message: '预计明日下午将出现6-7级大风，请做好防范措施',
    time: '2024-10-15 14:30',
    affectedFields: ['东区1号地', '西区2号地'],
  },
  {
    id: 'alert-2',
    type: '低温冻害',
    level: '警报',
    message: '预计后天凌晨最低温度将降至2℃，注意防冻',
    time: '2024-10-15 10:20',
    affectedFields: ['南区3号地'],
  },
];

// 生成测试预报数据
const generateTestForecast = (): WeatherForecast[] => [
  { day: '今天', weather: '多云', tempRange: '12-25°C', icon: 'cloud', description: '多云天气，温度适宜' },
  { day: '明天', weather: '大风', tempRange: '10-22°C', icon: 'wind', description: '风力较大，注意防范' },
  { day: '后天', weather: '小雨', tempRange: '8-18°C', icon: 'rain', description: '有小雨，携带雨具' },
  { day: '周四', weather: '晴', tempRange: '12-26°C', icon: 'sun', description: '晴朗天气，光照充足' },
  { day: '周五', weather: '多云', tempRange: '14-27°C', icon: 'cloud', description: '多云，温度上升' },
  { day: '周六', weather: '晴', tempRange: '15-28°C', icon: 'sun', description: '晴天，适宜户外活动' },
  { day: '周日', weather: '多云', tempRange: '13-25°C', icon: 'cloud', description: '多云，天气稳定' },
];

// 计算统计数据
const calculateStatistics = (data: WeatherData[]): WeatherStatistics => {
  if (data.length === 0) {
    return {
      temperature: { max: 0, min: 0, avg: 0, range: 0 },
      precipitation: { total: 0, maxHourly: 0, timeRange: '', intensity: '无' },
      wind: { maxSpeed: 0, avgSpeed: 0, level: '无风', direction: '无' },
      other: { avgHumidity: 0, totalSunlight: 0, avgPressure: 0 },
    };
  }

  const temperatures = data.map(d => d.temperature);
  const maxTemp = Math.max(...temperatures);
  const minTemp = Math.min(...temperatures);
  const avgTemp = temperatures.reduce((sum, t) => sum + t, 0) / temperatures.length;

  const totalRainfall = data.reduce((sum, d) => sum + d.rainfall, 0);
  const maxRainfall = Math.max(...data.map(d => d.rainfall));

  const windSpeeds = data.map(d => d.windSpeed);
  const maxWindSpeed = Math.max(...windSpeeds);
  const avgWindSpeed = windSpeeds.reduce((sum, w) => sum + w, 0) / windSpeeds.length;

  const avgHumidity = data.reduce((sum, d) => sum + d.humidity, 0) / data.length;
  const totalSunlight = data.reduce((sum, d) => sum + d.sunlight, 0);
  const avgPressure = data.reduce((sum, d) => sum + d.pressure, 0) / data.length;

  return {
    temperature: {
      max: maxTemp,
      min: minTemp,
      avg: Math.round(avgTemp * 10) / 10,
      range: maxTemp - minTemp,
    },
    precipitation: {
      total: totalRainfall,
      maxHourly: maxRainfall,
      timeRange: '18:00-21:00',
      intensity: totalRainfall > 50 ? '暴雨' : totalRainfall > 25 ? '大雨' : totalRainfall > 10 ? '中雨' : totalRainfall > 0 ? '小雨' : '无',
    },
    wind: {
      maxSpeed: Math.round(maxWindSpeed * 10) / 10,
      avgSpeed: Math.round(avgWindSpeed * 10) / 10,
      level: maxWindSpeed > 10 ? '5-6级' : maxWindSpeed > 5 ? '3-4级' : '1-2级',
      direction: '东南风',
    },
    other: {
      avgHumidity: Math.round(avgHumidity),
      totalSunlight,
      avgPressure: Math.round(avgPressure),
    },
  };
};

// 检测灾害天气
const checkWeatherAlerts = (data: WeatherData[]): WeatherAlert[] => {
  const alerts: WeatherAlert[] = [];

  data.forEach((d) => {
    // 低温冻害预警（温度低于3°C）
    if (d.temperature <= 3) {
      alerts.push({
        id: `alert-freeze-${d.time}`,
        type: '低温冻害',
        level: '警报',
        message: `预计${d.time}温度将降至${d.temperature}°C，请做好防冻措施`,
        time: new Date().toLocaleString('zh-CN'),
        affectedFields: ['东区1号地', '西区2号地', '南区3号地'],
      });
    }

    // 大风预警（风速大于10m/s）
    if (d.windSpeed >= 10) {
      alerts.push({
        id: `alert-wind-${d.time}`,
        type: '大风',
        level: '预警',
        message: `预计${d.time}风速将达到${d.windSpeed}m/s，请加固设施`,
        time: new Date().toLocaleString('zh-CN'),
        affectedFields: ['东区1号地', '西区2号地'],
      });
    }

    // 暴雨预警（3小时降雨量大于50mm）
    if (d.rainfall >= 50) {
      alerts.push({
        id: `alert-rain-${d.time}`,
        type: '暴雨',
        level: '紧急',
        message: `预计${d.time}降雨量将达到${d.rainfall}mm，请注意排涝`,
        time: new Date().toLocaleString('zh-CN'),
        affectedFields: ['南区3号地'],
      });
    }

    // 高温预警（温度高于35°C）
    if (d.temperature >= 35) {
      alerts.push({
        id: `alert-heat-${d.time}`,
        type: '高温',
        level: '预警',
        message: `预计${d.time}温度将达到${d.temperature}°C，注意防暑降温`,
        time: new Date().toLocaleString('zh-CN'),
        affectedFields: ['东区1号地'],
      });
    }
  });

  return alerts;
};

// Reducer函数
export function weatherDataReducer(state: WeatherDataState, action: WeatherDataAction): WeatherDataState {
  switch (action.type) {
    case 'SET_WEATHER_DATA':
      const statistics = calculateStatistics(action.payload);
      const newAlerts = checkWeatherAlerts(action.payload);
      return {
        ...state,
        weatherData: action.payload,
        statistics,
        weatherAlerts: [...state.weatherAlerts, ...newAlerts],
      };

    case 'SET_WEATHER_ALERTS':
      return { ...state, weatherAlerts: action.payload };

    case 'SET_WEATHER_FORECAST':
      return { ...state, weatherForecast: action.payload };

    case 'SET_WEATHER_STATION':
      return { ...state, weatherStation: action.payload };

    case 'SET_FILTERS':
      return {
        ...state,
        filters: { ...state.filters, ...action.payload },
        // 重新生成对应时间范围的数据
        weatherData: generateTestData(action.payload.timeRange || state.filters.timeRange),
      };

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

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

    case 'ACKNOWLEDGE_ALERT':
      return {
        ...state,
        acknowledgedAlerts: [...state.acknowledgedAlerts, action.payload],
      };

    case 'ACKNOWLEDGE_ALL_ALERTS':
      const allAlertIds = state.weatherAlerts.map(alert => alert.id);
      return {
        ...state,
        acknowledgedAlerts: allAlertIds,
      };

    case 'SET_REFRESHING':
      return { ...state, isRefreshing: action.payload };

    case 'SET_LAST_UPDATE_TIME':
      return { ...state, lastUpdateTime: action.payload };

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

    case 'ADD_WEATHER_ALERT':
      return {
        ...state,
        weatherAlerts: [action.payload, ...state.weatherAlerts],
      };

    case 'REMOVE_WEATHER_ALERT':
      return {
        ...state,
        weatherAlerts: state.weatherAlerts.filter(alert => alert.id !== action.payload),
      };

    case 'UPDATE_WEATHER_DATA':
      const updatedStatistics = calculateStatistics(action.payload);
      return {
        ...state,
        weatherData: action.payload,
        statistics: updatedStatistics,
      };

    case 'LOAD_FROM_STORAGE':
      try {
        const stored = localStorage.getItem('weatherData');
        if (stored) {
          const parsedData = JSON.parse(stored);
          return {
            ...state,
            ...parsedData,
            weatherData: parsedData.weatherData || generateTestData('24h'),
            weatherAlerts: parsedData.weatherAlerts || generateTestAlerts(),
            weatherForecast: parsedData.weatherForecast || generateTestForecast(),
          };
        } else {
          // 首次加载，初始化测试数据
          const initialData = {
            weatherData: generateTestData('24h'),
            weatherAlerts: generateTestAlerts(),
            weatherForecast: generateTestForecast(),
            lastUpdateTime: new Date().toLocaleString('zh-CN'),
          };
          localStorage.setItem('weatherData', JSON.stringify(initialData));
          return {
            ...state,
            ...initialData,
          };
        }
      } catch (error) {
        console.error('Failed to load weather data from storage:', error);
        return state;
      }

    case 'SAVE_TO_STORAGE':
      try {
        const dataToSave = {
          weatherStation: state.weatherStation,
          filters: state.filters,
          weatherData: state.weatherData,
          weatherAlerts: state.weatherAlerts,
          weatherForecast: state.weatherForecast,
          lastUpdateTime: state.lastUpdateTime,
        };
        localStorage.setItem('weatherData', JSON.stringify(dataToSave));
      } catch (error) {
        console.error('Failed to save weather data to storage:', error);
      }
      return state;

    default:
      return state;
  }
}

// 工具函数
export const getAlertColor = (level: string) => {
  switch (level) {
    case '预警': return 'bg-yellow-500';
    case '警报': return 'bg-orange-500';
    case '紧急': return 'bg-red-500';
    default: return 'bg-gray-500';
  }
};

export const getWeatherIcon = (weather: string) => {
  switch (weather) {
    case '晴': return 'sun';
    case '多云': return 'cloud';
    case '阴': return 'cloud';
    case '小雨': return 'rain';
    case '中雨': return 'rain';
    case '大雨': return 'rain';
    case '暴雨': return 'rain';
    case '大风': return 'wind';
    default: return 'cloud';
  }
};

export const formatTemperature = (temp: number) => `${temp}°C`;
export const formatWindSpeed = (speed: number) => `${speed} m/s`;
export const formatRainfall = (rainfall: number) => `${rainfall} mm`;
export const formatSunlight = (sunlight: number) => `${sunlight} W/m²`;
export const formatPressure = (pressure: number) => `${pressure} hPa`;