'use client';

import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { WeatherData } from './weatherDataReducer';
import { Download, Search, Calendar } from 'lucide-react';

interface WeatherHistoryProps {
  weatherData: WeatherData[];
  lastUpdateTime: string;
}

export default function WeatherHistory({ weatherData, lastUpdateTime }: WeatherHistoryProps) {
  const handleExportData = () => {
    // 生成CSV数据
    const headers = ['时间', '温度(°C)', '湿度(%)', '风速(m/s)', '降雨量(mm)', '光照(W/m²)', '气压(hPa)'];
    const rows = weatherData.map(data => [
      data.time,
      data.temperature,
      data.humidity,
      data.windSpeed,
      data.rainfall,
      data.sunlight,
      data.pressure,
    ]);

    const csvContent = [
      headers.join(','),
      ...rows.map(row => row.join(',')),
    ].join('\n');

    // 创建下载链接
    const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    link.setAttribute('href', url);
    link.setAttribute('download', `气象数据_${new Date().toLocaleDateString()}.csv`);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  return (
    <div className="space-y-4">
      <Card className="p-6">
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-lg font-semibold">历史气象数据查询</h3>
          <div className="flex gap-2">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground" />
              <Input
                placeholder="搜索时间点..."
                className="pl-10 w-48"
              />
            </div>
            <Button variant="outline" size="sm" onClick={handleExportData}>
              <Download className="w-4 h-4 mr-2" />
              导出数据
            </Button>
          </div>
        </div>

        {/* 数据概览 */}
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6 p-4 bg-muted rounded-lg">
          <div className="text-center">
            <div className="text-2xl font-bold text-blue-600">{weatherData.length}</div>
            <div className="text-xs text-muted-foreground">数据点</div>
          </div>
          <div className="text-center">
            <div className="text-2xl font-bold text-green-600">
              {Math.max(...weatherData.map(d => d.temperature))}°C
            </div>
            <div className="text-xs text-muted-foreground">最高温度</div>
          </div>
          <div className="text-center">
            <div className="text-2xl font-bold text-cyan-600">
              {weatherData.reduce((sum, d) => sum + d.rainfall, 0)}mm
            </div>
            <div className="text-xs text-muted-foreground">总降雨量</div>
          </div>
          <div className="text-center">
            <div className="text-2xl font-bold text-purple-600">
              {Math.round(weatherData.reduce((sum, d) => sum + d.windSpeed, 0) / weatherData.length)}m/s
            </div>
            <div className="text-xs text-muted-foreground">平均风速</div>
          </div>
        </div>

        {/* 数据表格 */}
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-muted">
              <tr>
                <th className="px-4 py-3 text-left text-xs font-medium">时间</th>
                <th className="px-4 py-3 text-center text-xs font-medium">温度(°C)</th>
                <th className="px-4 py-3 text-center text-xs font-medium">湿度(%)</th>
                <th className="px-4 py-3 text-center text-xs font-medium">风速(m/s)</th>
                <th className="px-4 py-3 text-center text-xs font-medium">降雨量(mm)</th>
                <th className="px-4 py-3 text-center text-xs font-medium">光照(W/m²)</th>
                <th className="px-4 py-3 text-center text-xs font-medium">气压(hPa)</th>
              </tr>
            </thead>
            <tbody>
              {weatherData.map((data, index) => (
                <tr
                  key={index}
                  className="border-t hover:bg-muted/50 transition-colors"
                >
                  <td className="px-4 py-3 text-sm">
                    <div className="flex items-center gap-2">
                      <Calendar className="w-4 h-4 text-muted-foreground" />
                      {data.time}
                    </div>
                  </td>
                  <td className="px-4 py-3 text-center">
                    <Badge
                      variant={data.temperature > 25 ? 'destructive' : data.temperature < 15 ? 'secondary' : 'outline'}
                      className="font-light"
                    >
                      {data.temperature}
                    </Badge>
                  </td>
                  <td className="px-4 py-3 text-center">
                    <Badge
                      variant={data.humidity > 70 ? 'outline' : 'secondary'}
                      className="font-light"
                    >
                      {data.humidity}
                    </Badge>
                  </td>
                  <td className="px-4 py-3 text-center">
                    <Badge
                      variant={data.windSpeed > 5 ? 'destructive' : 'outline'}
                      className="font-light"
                    >
                      {data.windSpeed}
                    </Badge>
                  </td>
                  <td className="px-4 py-3 text-center">
                    {data.rainfall > 0 ? (
                      <Badge variant="outline" className="font-light bg-blue-50 text-blue-700 border-blue-200">
                        {data.rainfall}
                      </Badge>
                    ) : (
                      <span className="text-muted-foreground">-</span>
                    )}
                  </td>
                  <td className="px-4 py-3 text-center">
                    <Badge
                      variant={data.sunlight > 500 ? 'outline' : 'secondary'}
                      className="font-light"
                    >
                      {data.sunlight}
                    </Badge>
                  </td>
                  <td className="px-4 py-3 text-center text-sm">
                    {data.pressure}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {weatherData.length === 0 && (
          <div className="text-center py-8 text-muted-foreground">
            <Calendar className="w-12 h-12 mx-auto mb-4 opacity-50" />
            <p>暂无历史数据</p>
            <p className="text-sm mt-1">请等待气象数据更新</p>
          </div>
        )}

        {/* 数据更新信息 */}
        <div className="mt-4 pt-4 border-t text-xs text-muted-foreground">
          <div className="flex items-center justify-between">
            <span>数据来源：{weatherData.length > 0 ? '自动气象站' : '暂无数据'}</span>
            <span>最后更新：{lastUpdateTime || '未更新'}</span>
          </div>
        </div>
      </Card>

      {/* 数据统计卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <Card className="p-4">
          <h4 className="font-medium mb-3">温度分布</h4>
          <div className="space-y-2 text-sm">
            <div className="flex justify-between">
              <span className="text-muted-foreground">高温天数:</span>
              <span className="font-medium">{weatherData.filter(d => d.temperature > 30).length} 天</span>
            </div>
            <div className="flex justify-between">
              <span className="text-muted-foreground">低温天数:</span>
              <span className="font-medium">{weatherData.filter(d => d.temperature < 10).length} 天</span>
            </div>
            <div className="flex justify-between">
              <span className="text-muted-foreground">适宜天数:</span>
              <span className="font-medium">{weatherData.filter(d => d.temperature >= 15 && d.temperature <= 25).length} 天</span>
            </div>
          </div>
        </Card>

        <Card className="p-4">
          <h4 className="font-medium mb-3">降水统计</h4>
          <div className="space-y-2 text-sm">
            <div className="flex justify-between">
              <span className="text-muted-foreground">降雨天数:</span>
              <span className="font-medium">{weatherData.filter(d => d.rainfall > 0).length} 天</span>
            </div>
            <div className="flex justify-between">
              <span className="text-muted-foreground">最大降雨:</span>
              <span className="font-medium">{Math.max(...weatherData.map(d => d.rainfall))} mm</span>
            </div>
            <div className="flex justify-between">
              <span className="text-muted-foreground">降雨强度:</span>
              <span className="font-medium">小雨</span>
            </div>
          </div>
        </Card>

        <Card className="p-4">
          <h4 className="font-medium mb-3">风力条件</h4>
          <div className="space-y-2 text-sm">
            <div className="flex justify-between">
              <span className="text-muted-foreground">大风天数:</span>
              <span className="font-medium">{weatherData.filter(d => d.windSpeed > 5).length} 天</span>
            </div>
            <div className="flex justify-between">
              <span className="text-muted-foreground">静风天数:</span>
              <span className="font-medium">{weatherData.filter(d => d.windSpeed < 1).length} 天</span>
            </div>
            <div className="flex justify-between">
              <span className="text-muted-foreground">主导风向:</span>
              <span className="font-medium">东南风</span>
            </div>
          </div>
        </Card>
      </div>
    </div>
  );
}