'use client';

import { Button } from '@/components/ui/button';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { RefreshCw } from 'lucide-react';
import { WeatherDataState, WeatherDataAction } from './weatherDataReducer';
import WeatherAlerts from './WeatherAlerts';
import RealtimeWeatherCards from './RealtimeWeatherCards';
import ControlPanel from './ControlPanel';
import WeatherCharts from './WeatherCharts';
import WeatherForecast from './WeatherForecast';
import WeatherHistory from './WeatherHistory';
import WeatherAnalysis from './WeatherAnalysis';
import UsageGuide from './UsageGuide';

interface WeatherContentProps {
  state: WeatherDataState;
  dispatch: React.Dispatch<WeatherDataAction>;
}

export default function WeatherContent({ state, dispatch }: WeatherContentProps) {
  const handleRefreshData = async () => {
    if (!state.weatherStation.enabled) {
      return;
    }

    dispatch({ type: 'SET_REFRESHING', payload: true });

    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1500));

      // 生成新的测试数据
      const newData = state.weatherData.map(d => ({
        ...d,
        temperature: d.temperature + (Math.random() - 0.5) * 2,
        humidity: Math.max(20, Math.min(95, d.humidity + (Math.random() - 0.5) * 5)),
        windSpeed: Math.max(0, d.windSpeed + (Math.random() - 0.5) * 1),
        rainfall: Math.max(0, d.rainfall + Math.random() * 2),
        sunlight: Math.max(0, d.sunlight + (Math.random() - 0.5) * 50),
        pressure: d.pressure + (Math.random() - 0.5) * 2,
      }));

      dispatch({ type: 'UPDATE_WEATHER_DATA', payload: newData });
      dispatch({ type: 'SET_LAST_UPDATE_TIME', payload: new Date().toLocaleString('zh-CN') });
    } catch (error) {
      console.error('Failed to refresh weather data:', error);
    } finally {
      dispatch({ type: 'SET_REFRESHING', payload: false });
    }
  };

  return (
    <div className="space-y-6">
      {/* 操作按钮区域 */}
      <div className="flex items-center justify-between">
        <div>
        <h2 className="text-xl text-green-800 dark:text-green-200">气象监测</h2>
        <p className="text-sm text-muted-foreground mt-1">
          实时气象数据、历史数据分析与灾害天气预警
        </p>
        </div>
        <div className="flex gap-2">
          <Button
            variant="outline"
            onClick={handleRefreshData}
            disabled={state.isRefreshing}
          >
            <RefreshCw className={`w-4 h-4 mr-2 ${state.isRefreshing ? 'animate-spin' : ''}`} />
            {state.isRefreshing ? '刷新中...' : '刷新数据'}
          </Button>
        </div>
      </div>

      {/* 天气预警 */}
      <WeatherAlerts state={state} dispatch={dispatch} />

      {/* 实时气象数据卡片 */}
      <RealtimeWeatherCards weatherData={state.weatherData} />

      {/* 控制面板 */}
      <ControlPanel state={state} dispatch={dispatch} />

      {/* 主要内容区域 */}
      <Tabs value={state.activeTab} onValueChange={(value) => dispatch({ type: 'SET_ACTIVE_TAB', payload: value })}>
        <TabsList className="grid w-full grid-cols-4">
          <TabsTrigger value="charts">数据曲线</TabsTrigger>
          <TabsTrigger value="forecast">天气预报</TabsTrigger>
          <TabsTrigger value="history">历史数据</TabsTrigger>
          <TabsTrigger value="analysis">数据分析</TabsTrigger>
        </TabsList>

        <TabsContent value="charts" className="space-y-4">
          <WeatherCharts
            weatherData={state.weatherData}
            timeRange={state.filters.timeRange}
          />
        </TabsContent>

        <TabsContent value="forecast" className="space-y-4">
          <WeatherForecast
            weatherForecast={state.weatherForecast}
          />
        </TabsContent>

        <TabsContent value="history" className="space-y-4">
          <WeatherHistory
            weatherData={state.weatherData}
            lastUpdateTime={state.lastUpdateTime}
          />
        </TabsContent>

        <TabsContent value="analysis" className="space-y-4">
          <WeatherAnalysis
            statistics={state.statistics}
            weatherData={state.weatherData}
          />
        </TabsContent>
      </Tabs>

      {/* 使用说明 */}
      <UsageGuide />
    </div>
  );
}