import { useState, useEffect } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Input } from '../ui/input';
import { Badge } from '../ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '../ui/dialog';
import { Label } from '../ui/label';
import {
  Cloud,
  CloudRain,
  Wind,
  Thermometer,
  Droplets,
  Sun,
  AlertTriangle,
  TrendingUp,
  Upload,
  Bell,
  Eye,
  Calendar,
  Activity,
  Zap,
  RefreshCw,
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';
import { LineChart, Line, BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend } from 'recharts';

interface WeatherData {
  time: string;
  temperature: number;
  humidity: number;
  windSpeed: number;
  rainfall: number;
  sunlight: number;
  pressure: number;
}

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

export function WeatherMonitoring() {
  const [selectedField, setSelectedField] = useState('field-1');
  const [timeRange, setTimeRange] = useState<'24h' | '7d' | '30d'>('24h');
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [acknowledgedAlerts, setAcknowledgedAlerts] = useState<string[]>([]);

  // 气象站配置（从localStorage或配置中心获取）
  const weatherStation = {
    enabled: true,
    apiEndpoint: 'https://api.weather.example.com/data',
    apiKey: 'YOUR_API_KEY_HERE',
    latitude: 39.9042,
    longitude: 116.4074,
  };

  // 根据时间范围生成气象数据
  const getWeatherDataByRange = (range: '24h' | '7d' | '30d'): WeatherData[] => {
    if (range === '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 (range === '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 weatherData = getWeatherDataByRange(timeRange);

  // 模拟天气预警
  const weatherAlerts: 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号地'],
    },
  ];

  // 从API获取气象数据
  const fetchWeatherData = async () => {
    if (!weatherStation.enabled) {
      toast.error('气象站未启用，请先配置API接口');
      return;
    }

    setIsRefreshing(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1500));
      
      // 实际项目中，这里应该调用真实的API
      // const response = await fetch(`${weatherStation.apiEndpoint}?key=${weatherStation.apiKey}&location=${weatherStation.latitude},${weatherStation.longitude}`);
      // const data = await response.json();
      
      toast.success('气象数据已更新！最新数据已同步');
    } catch (error) {
      toast.error('获取气象数据失败，请检查API配置');
    } finally {
      setIsRefreshing(false);
    }
  };

  // 自动刷新气象数据
  useEffect(() => {
    // 首次加载
    fetchWeatherData();
    
    // 每15分钟自动刷新一次
    const interval = setInterval(() => {
      fetchWeatherData();
    }, 15 * 60 * 1000);

    return () => clearInterval(interval);
  }, []);

  // 检测灾害天气并发送预警
  const checkWeatherAlerts = (data: WeatherData[]) => {
    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;
  };

  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';
    }
  };



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

      {/* 天气预警 */}
      {weatherAlerts.filter(alert => !acknowledgedAlerts.includes(alert.id)).length > 0 && (
        <div className="space-y-2">
          {weatherAlerts.filter(alert => !acknowledgedAlerts.includes(alert.id)).map((alert) => (
            <Card key={alert.id} className="p-4 border-l-4 border-l-orange-500 bg-orange-50">
              <div className="flex items-start gap-4">
                <AlertTriangle className="w-6 h-6 text-orange-600 flex-shrink-0 mt-0.5" />
                <div className="flex-1">
                  <div className="flex items-center gap-3 mb-2">
                    <Badge className={`${getAlertColor(alert.level)} text-white`}>
                      {alert.level}
                    </Badge>
                    <Badge variant="outline">{alert.type}</Badge>
                    <span className="text-xs text-muted-foreground">{alert.time}</span>
                  </div>
                  <p className="text-sm mb-2">{alert.message}</p>
                  <div className="flex items-center gap-2 text-xs text-muted-foreground">
                    <span>影响地块:</span>
                    {alert.affectedFields.map((field, index) => (
                      <Badge key={index} variant="outline" className="text-xs">
                        {field}
                      </Badge>
                    ))}
                  </div>
                </div>
                <Button 
                  size="sm" 
                  className="bg-green-600 hover:bg-green-700"
                  onClick={() => {
                    setAcknowledgedAlerts([...acknowledgedAlerts, alert.id]);
                    toast.success('已知晓预警信息');
                  }}
                >
                  知晓
                </Button>
              </div>
            </Card>
          ))}
        </div>
      )}

      {/* 实时气象数据 */}
      <div className="grid grid-cols-6 gap-4">
        <Card className="p-4 bg-gradient-to-br from-red-50 to-red-100">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">温度</p>
              <p className="mt-2 text-2xl text-red-600">25°C</p>
              <p className="text-xs text-green-600 mt-1">↑ 3°C</p>
            </div>
            <Thermometer className="w-10 h-10 text-red-600 opacity-50" />
          </div>
        </Card>

        <Card className="p-4 bg-gradient-to-br from-blue-50 to-blue-100">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">湿度</p>
              <p className="mt-2 text-2xl text-blue-600">48%</p>
              <p className="text-xs text-red-600 mt-1">↓ 7%</p>
            </div>
            <Droplets className="w-10 h-10 text-blue-600 opacity-50" />
          </div>
        </Card>

        <Card className="p-4 bg-gradient-to-br from-cyan-50 to-cyan-100">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">风速</p>
              <p className="mt-2 text-2xl text-cyan-600">5.2 m/s</p>
              <p className="text-xs text-green-600 mt-1">↑ 0.7 m/s</p>
            </div>
            <Wind className="w-10 h-10 text-cyan-600 opacity-50" />
          </div>
        </Card>

        <Card className="p-4 bg-gradient-to-br from-indigo-50 to-indigo-100">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">降雨量</p>
              <p className="mt-2 text-2xl text-indigo-600">7 mm</p>
              <p className="text-xs text-muted-foreground mt-1">今日累计</p>
            </div>
            <CloudRain className="w-10 h-10 text-indigo-600 opacity-50" />
          </div>
        </Card>

        <Card className="p-4 bg-gradient-to-br from-yellow-50 to-yellow-100">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">光照强度</p>
              <p className="mt-2 text-2xl text-yellow-600">680</p>
              <p className="text-xs text-muted-foreground mt-1">W/m²</p>
            </div>
            <Sun className="w-10 h-10 text-yellow-600 opacity-50" />
          </div>
        </Card>

        <Card className="p-4 bg-gradient-to-br from-purple-50 to-purple-100">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">气压</p>
              <p className="mt-2 text-2xl text-purple-600">1013</p>
              <p className="text-xs text-muted-foreground mt-1">hPa</p>
            </div>
            <Activity className="w-10 h-10 text-purple-600 opacity-50" />
          </div>
        </Card>
      </div>

      {/* 控制面板 */}
      <Card className="p-4">
        <div className="flex items-center gap-4">
          <div className="flex-1">
            <label className="text-xs text-muted-foreground mb-2 block">选择地块</label>
            <Select value={selectedField} onValueChange={setSelectedField}>
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="field-1">东区1号地</SelectItem>
                <SelectItem value="field-2">西区2号地</SelectItem>
                <SelectItem value="field-3">南区3号地</SelectItem>
              </SelectContent>
            </Select>
          </div>

          <div className="flex-1">
            <label className="text-xs text-muted-foreground mb-2 block">时间范围</label>
            <div className="flex gap-2">
              <Button
                variant={timeRange === '24h' ? 'default' : 'outline'}
                size="sm"
                onClick={() => setTimeRange('24h')}
                className="flex-1"
              >
                24小时
              </Button>
              <Button
                variant={timeRange === '7d' ? 'default' : 'outline'}
                size="sm"
                onClick={() => setTimeRange('7d')}
                className="flex-1"
              >
                7天
              </Button>
              <Button
                variant={timeRange === '30d' ? 'default' : 'outline'}
                size="sm"
                onClick={() => setTimeRange('30d')}
                className="flex-1"
              >
                30天
              </Button>
            </div>
          </div>
        </div>
      </Card>

      <Tabs defaultValue="charts">
        <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">
          <Card className="p-6">
            <h3 className="mb-4">温度变化曲线</h3>
            <ResponsiveContainer width="100%" height={280}>
              <LineChart data={weatherData} margin={{ top: 5, right: 30, left: 20, bottom: 5 }}>
                <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
                <XAxis 
                  dataKey="time" 
                  tick={{ fontSize: 12, fill: '#6b7280' }}
                  label={{ value: '时间', position: 'insideBottom', offset: -5, style: { fontSize: 12, fill: '#6b7280' } }}
                />
                <YAxis 
                  tick={{ fontSize: 12, fill: '#6b7280' }}
                  label={{ value: '温度 (°C)', angle: -90, position: 'insideLeft', style: { fontSize: 12, fill: '#6b7280' } }}
                />
                <Tooltip 
                  contentStyle={{ backgroundColor: '#fff', border: '1px solid #e5e7eb', borderRadius: '6px' }}
                  formatter={(value: number) => [`${value}°C`, '温度']}
                />
                <Line 
                  type="monotone" 
                  dataKey="temperature" 
                  stroke="#dc2626" 
                  strokeWidth={2}
                  dot={{ fill: '#dc2626', r: 4 }}
                  activeDot={{ r: 6 }}
                />
              </LineChart>
            </ResponsiveContainer>
          </Card>

          <div className="grid grid-cols-2 gap-4">
            <Card className="p-6">
              <h3 className="mb-4">湿度变化曲线</h3>
              <ResponsiveContainer width="100%" height={220}>
                <LineChart data={weatherData} margin={{ top: 5, right: 30, left: 20, bottom: 5 }}>
                  <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
                  <XAxis 
                    dataKey="time" 
                    tick={{ fontSize: 12, fill: '#6b7280' }}
                  />
                  <YAxis 
                    tick={{ fontSize: 12, fill: '#6b7280' }}
                    label={{ value: '湿度 (%)', angle: -90, position: 'insideLeft', style: { fontSize: 12, fill: '#6b7280' } }}
                  />
                  <Tooltip 
                    contentStyle={{ backgroundColor: '#fff', border: '1px solid #e5e7eb', borderRadius: '6px' }}
                    formatter={(value: number) => [`${value}%`, '湿度']}
                  />
                  <Line 
                    type="monotone" 
                    dataKey="humidity" 
                    stroke="#2563eb" 
                    strokeWidth={2}
                    dot={{ fill: '#2563eb', r: 3 }}
                  />
                </LineChart>
              </ResponsiveContainer>
            </Card>

            <Card className="p-6">
              <h3 className="mb-4">风速变化曲线</h3>
              <ResponsiveContainer width="100%" height={220}>
                <LineChart data={weatherData} margin={{ top: 5, right: 30, left: 20, bottom: 5 }}>
                  <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
                  <XAxis 
                    dataKey="time" 
                    tick={{ fontSize: 12, fill: '#6b7280' }}
                  />
                  <YAxis 
                    tick={{ fontSize: 12, fill: '#6b7280' }}
                    label={{ value: '风速 (m/s)', angle: -90, position: 'insideLeft', style: { fontSize: 12, fill: '#6b7280' } }}
                  />
                  <Tooltip 
                    contentStyle={{ backgroundColor: '#fff', border: '1px solid #e5e7eb', borderRadius: '6px' }}
                    formatter={(value: number) => [`${value} m/s`, '风速']}
                  />
                  <Line 
                    type="monotone" 
                    dataKey="windSpeed" 
                    stroke="#06b6d4" 
                    strokeWidth={2}
                    dot={{ fill: '#06b6d4', r: 3 }}
                  />
                </LineChart>
              </ResponsiveContainer>
            </Card>

            <Card className="p-6">
              <h3 className="mb-4">降雨量统计</h3>
              <ResponsiveContainer width="100%" height={220}>
                <BarChart data={weatherData} margin={{ top: 5, right: 30, left: 20, bottom: 5 }}>
                  <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
                  <XAxis 
                    dataKey="time" 
                    tick={{ fontSize: 12, fill: '#6b7280' }}
                  />
                  <YAxis 
                    tick={{ fontSize: 12, fill: '#6b7280' }}
                    label={{ value: '降雨量 (mm)', angle: -90, position: 'insideLeft', style: { fontSize: 12, fill: '#6b7280' } }}
                  />
                  <Tooltip 
                    contentStyle={{ backgroundColor: '#fff', border: '1px solid #e5e7eb', borderRadius: '6px' }}
                    formatter={(value: number) => [`${value} mm`, '降雨量']}
                  />
                  <Bar 
                    dataKey="rainfall" 
                    fill="#6366f1" 
                    radius={[4, 4, 0, 0]}
                  />
                </BarChart>
              </ResponsiveContainer>
            </Card>

            <Card className="p-6">
              <h3 className="mb-4">光照强度曲线</h3>
              <ResponsiveContainer width="100%" height={220}>
                <LineChart data={weatherData} margin={{ top: 5, right: 30, left: 20, bottom: 5 }}>
                  <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
                  <XAxis 
                    dataKey="time" 
                    tick={{ fontSize: 12, fill: '#6b7280' }}
                  />
                  <YAxis 
                    tick={{ fontSize: 12, fill: '#6b7280' }}
                    label={{ value: '光照 (W/m²)', angle: -90, position: 'insideLeft', style: { fontSize: 12, fill: '#6b7280' } }}
                  />
                  <Tooltip 
                    contentStyle={{ backgroundColor: '#fff', border: '1px solid #e5e7eb', borderRadius: '6px' }}
                    formatter={(value: number) => [`${value} W/m²`, '光照强度']}
                  />
                  <Line 
                    type="monotone" 
                    dataKey="sunlight" 
                    stroke="#eab308" 
                    strokeWidth={2}
                    dot={{ fill: '#eab308', r: 3 }}
                  />
                </LineChart>
              </ResponsiveContainer>
            </Card>
          </div>
        </TabsContent>

        {/* 天气预报 */}
        <TabsContent value="forecast" className="space-y-4">
          <div className="grid grid-cols-7 gap-4">
            {[
              { day: '今天', weather: '多云', temp: '12-25°C', icon: <Cloud className="w-8 h-8" /> },
              { day: '明天', weather: '大风', temp: '10-22°C', icon: <Wind className="w-8 h-8" /> },
              { day: '后天', weather: '小雨', temp: '8-18°C', icon: <CloudRain className="w-8 h-8" /> },
              { day: '周四', weather: '晴', temp: '12-26°C', icon: <Sun className="w-8 h-8" /> },
              { day: '周五', weather: '多云', temp: '14-27°C', icon: <Cloud className="w-8 h-8" /> },
              { day: '周六', weather: '晴', temp: '15-28°C', icon: <Sun className="w-8 h-8" /> },
              { day: '周日', weather: '多云', temp: '13-25°C', icon: <Cloud className="w-8 h-8" /> },
            ].map((forecast, index) => (
              <Card key={index} className="p-4 text-center">
                <p className="text-sm font-medium mb-2">{forecast.day}</p>
                <div className="flex justify-center text-blue-600 mb-2">
                  {forecast.icon}
                </div>
                <p className="text-xs text-muted-foreground mb-1">{forecast.weather}</p>
                <p className="text-sm">{forecast.temp}</p>
              </Card>
            ))}
          </div>

          <Card className="p-6">
            <h3 className="mb-4">未来7天趋势</h3>
            <div className="relative h-64 border rounded-lg p-4">
              <svg className="w-full h-full">
                {/* 温度带 */}
                <defs>
                  <linearGradient id="tempGradient" x1="0%" y1="0%" x2="0%" y2="100%">
                    <stop offset="0%" stopColor="#ef4444" stopOpacity="0.3" />
                    <stop offset="100%" stopColor="#3b82f6" stopOpacity="0.3" />
                  </linearGradient>
                </defs>
                <polygon
                  points="0,30% 14%,25% 28%,35% 42%,28% 57%,22% 71%,20% 85%,25% 100%,30% 100%,70% 85%,75% 71%,80% 57%,78% 42%,82% 28%,85% 14%,75% 0,70%"
                  fill="url(#tempGradient)"
                  opacity="0.5"
                />
                <polyline
                  points="0,30% 14%,25% 28%,35% 42%,28% 57%,22% 71%,20% 85%,25% 100%,30%"
                  fill="none"
                  stroke="#ef4444"
                  strokeWidth="2"
                />
                <polyline
                  points="0,70% 14%,75% 28%,85% 42%,82% 57%,78% 71%,80% 85%,75% 100%,70%"
                  fill="none"
                  stroke="#3b82f6"
                  strokeWidth="2"
                />
              </svg>
            </div>
          </Card>
        </TabsContent>

        {/* 历史数据 */}
        <TabsContent value="history" className="space-y-4">
          <Card className="p-6">
            <h3 className="mb-4">历史气象数据查询</h3>
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-4 py-3 text-left text-xs">时间</th>
                    <th className="px-4 py-3 text-center text-xs">温度(°C)</th>
                    <th className="px-4 py-3 text-center text-xs">湿度(%)</th>
                    <th className="px-4 py-3 text-center text-xs">风速(m/s)</th>
                    <th className="px-4 py-3 text-center text-xs">降雨量(mm)</th>
                    <th className="px-4 py-3 text-center text-xs">光照(W/m²)</th>
                    <th className="px-4 py-3 text-center text-xs">气压(hPa)</th>
                  </tr>
                </thead>
                <tbody>
                  {weatherData.map((data, index) => (
                    <tr key={index} className="border-t hover:bg-gray-50">
                      <td className="px-4 py-3 text-sm">{data.time}</td>
                      <td className="px-4 py-3 text-center text-sm">{data.temperature}</td>
                      <td className="px-4 py-3 text-center text-sm">{data.humidity}</td>
                      <td className="px-4 py-3 text-center text-sm">{data.windSpeed}</td>
                      <td className="px-4 py-3 text-center text-sm">{data.rainfall}</td>
                      <td className="px-4 py-3 text-center text-sm">{data.sunlight}</td>
                      <td className="px-4 py-3 text-center text-sm">{data.pressure}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </Card>
        </TabsContent>

        {/* 数据分析 */}
        <TabsContent value="analysis" className="space-y-4">
          <div className="grid grid-cols-3 gap-4">
            <Card className="p-6">
              <h3 className="mb-4">温度统计</h3>
              <div className="space-y-3 text-sm">
                <div className="flex justify-between">
                  <span className="text-muted-foreground">最高温度:</span>
                  <span className="text-red-600 font-medium">25°C</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">最低温度:</span>
                  <span className="text-blue-600 font-medium">9°C</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">平均温度:</span>
                  <span className="font-medium">16.1°C</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">温差:</span>
                  <span className="font-medium">16°C</span>
                </div>
              </div>
            </Card>

            <Card className="p-6">
              <h3 className="mb-4">降水统计</h3>
              <div className="space-y-3 text-sm">
                <div className="flex justify-between">
                  <span className="text-muted-foreground">累计降雨:</span>
                  <span className="text-blue-600 font-medium">7 mm</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">最大降雨:</span>
                  <span className="font-medium">5 mm/3h</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">降雨时段:</span>
                  <span className="font-medium">18:00-21:00</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">降雨强度:</span>
                  <span className="text-green-600">小雨</span>
                </div>
              </div>
            </Card>

            <Card className="p-6">
              <h3 className="mb-4">风力统计</h3>
              <div className="space-y-3 text-sm">
                <div className="flex justify-between">
                  <span className="text-muted-foreground">最大风速:</span>
                  <span className="text-cyan-600 font-medium">5.2 m/s</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">平均风速:</span>
                  <span className="font-medium">3.3 m/s</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">风力等级:</span>
                  <span className="font-medium">3-4级</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">主导风向:</span>
                  <span className="font-medium">东南风</span>
                </div>
              </div>
            </Card>
          </div>

          <Card className="p-6">
            <h3 className="mb-4">气象条件评价</h3>
            <div className="grid grid-cols-2 gap-4">
              <div className="p-4 bg-green-50 border border-green-200 rounded-lg">
                <h4 className="text-green-900 mb-2">有利条件</h4>
                <ul className="text-sm text-green-800 space-y-1">
                  <li>• 温度适宜，利于作物生长</li>
                  <li>• 光照充足，光合作用强</li>
                  <li>• 适量降雨，补充土壤水分</li>
                </ul>
              </div>
              <div className="p-4 bg-orange-50 border border-orange-200 rounded-lg">
                <h4 className="text-orange-900 mb-2">注意事项</h4>
                <ul className="text-sm text-orange-800 space-y-1">
                  <li>• 白天温差较大，注意保温</li>
                  <li>• 风力较大，加固设施</li>
                  <li>• 关注未来天气变化</li>
                </ul>
              </div>
            </div>
          </Card>
        </TabsContent>
      </Tabs>

      {/* 气象API接口配置 */}
      <Card className="p-4 bg-blue-50 border-blue-200">
        <div className="flex items-start gap-2">
          <Zap className="w-5 h-5 text-blue-600 flex-shrink-0 mt-0.5" />
          <div className="text-sm text-blue-800">
            <p className="mb-2">气象监测功能说明：</p>
            <ul className="space-y-1 text-xs">
              <li>• <strong>API接口</strong>: 支持对接多种气象API（如中国气象局、和风天气等）</li>
              <li>• <strong>实时监控</strong>: 自动获取并更新气象站数据（每15分钟自动刷新）</li>
              <li>• <strong>数据可视化</strong>: 多种图表展示气象数据变化趋势</li>
              <li>• <strong>天气预报</strong>: 对接天气预报API，提供未来7天预报</li>
              <li>• <strong>灾害预警</strong>: 智能识别低温冻害（≤3°C）、大风（≥10m/s）、暴雨（≥50mm）、高温（≥35°C）</li>
            </ul>
          </div>
        </div>
      </Card>

    </div>
  );
}
