import { useState, useMemo, useEffect } from 'react';
import { Card } from '../../ui/card';
import { Button } from '../../ui/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../../ui/select';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';
import { Download, Calendar } from 'lucide-react';
import { machineryStorage } from '../../../lib/machineryStorage';
import { MachineryRecord } from '../../../types/machinery';

export function HistoryComparison() {
  const [compareType, setCompareType] = useState('year');
  const [selectedMachinery, setSelectedMachinery] = useState('all');
  const [selectedMetric, setSelectedMetric] = useState('area');
  const [machineryList, setMachineryList] = useState<MachineryRecord[]>([]);

  // 加载农机列表
  useEffect(() => {
    const machinery = machineryStorage.getAllMachinery();
    setMachineryList(machinery);
  }, []);

  // 指标配置
  const metricConfig = {
    area: { label: '作业面积', unit: '亩', multiplier: 1 },
    efficiency: { label: '作业效率', unit: '亩/小时', multiplier: 0.8 },
    cost: { label: '作业成本', unit: '元', multiplier: 3.5 },
    quality: { label: '作业质量', unit: '分', multiplier: 0.15 },
  };
  
  // 年度对比数据（按月）
  const yearComparisonData = [
    { month: '1月', year2023: 420, year2024: 480 },
    { month: '2月', year2023: 380, year2024: 410 },
    { month: '3月', year2023: 510, year2024: 580 },
    { month: '4月', year2023: 620, year2024: 680 },
    { month: '5月', year2023: 580, year2024: 650 },
    { month: '6月', year2023: 650, year2024: 720 },
    { month: '7月', year2023: 680, year2024: 750 },
    { month: '8月', year2023: 710, year2024: 780 },
    { month: '9月', year2023: 640, year2024: 700 },
    { month: '10月', year2023: 590, year2024: 660 },
    { month: '11月', year2023: 520, year2024: 580 },
    { month: '12月', year2023: 450, year2024: 520 },
  ];

  // 季度对比数据（按月）
  const quarterComparisonData = [
    { month: '1月', q1_2024: 480, q2_2024: 520 },
    { month: '2月', q1_2024: 410, q2_2024: 450 },
    { month: '3月', q1_2024: 580, q2_2024: 620 },
  ];

  // 月度对比数据（按天）
  const monthComparisonData = [
    { day: '1日', current: 15, previous: 12 },
    { day: '5日', current: 18, previous: 15 },
    { day: '10日', current: 22, previous: 19 },
    { day: '15日', current: 20, previous: 18 },
    { day: '20日', current: 25, previous: 21 },
    { day: '25日', current: 23, previous: 20 },
    { day: '30日', current: 21, previous: 17 },
  ];

  // 根据对比类型获取基础数据
  const baseData = useMemo(() => {
    switch (compareType) {
      case 'year':
        return yearComparisonData;
      case 'quarter':
        return quarterComparisonData;
      case 'month':
        return monthComparisonData;
      default:
        return yearComparisonData;
    }
  }, [compareType]);

  // 根据设备和指标转换数据
  const currentData = useMemo(() => {
    const config = metricConfig[selectedMetric as keyof typeof metricConfig];
    const multiplier = config.multiplier;
    
    // 如果选择了特定设备，应用设备系数（这里简化处理，实际应该从真实数据筛选）
    const deviceMultiplier = selectedMachinery === 'all' ? 1 : 0.9;
    
    return baseData.map(item => {
      const transformed: any = {};
      Object.keys(item).forEach(key => {
        if (typeof item[key as keyof typeof item] === 'number') {
          // 转换数值
          transformed[key] = Math.round(item[key as keyof typeof item] as number * multiplier * deviceMultiplier);
        } else {
          // 保留时间字段
          transformed[key] = item[key as keyof typeof item];
        }
      });
      return transformed;
    });
  }, [baseData, selectedMetric, selectedMachinery]);

  // 获取图表配置
  const chartConfig = useMemo(() => {
    switch (compareType) {
      case 'year':
        return {
          xDataKey: 'month',
          line1Key: 'year2023',
          line2Key: 'year2024',
          line1Name: '2023年',
          line2Name: '2024年',
        };
      case 'quarter':
        return {
          xDataKey: 'month',
          line1Key: 'q1_2024',
          line2Key: 'q2_2024',
          line1Name: '第一季度',
          line2Name: '第二季度',
        };
      case 'month':
        return {
          xDataKey: 'day',
          line1Key: 'previous',
          line2Key: 'current',
          line1Name: '上月',
          line2Name: '本月',
        };
      default:
        return {
          xDataKey: 'month',
          line1Key: 'year2023',
          line2Key: 'year2024',
          line1Name: '2023年',
          line2Name: '2024年',
        };
    }
  }, [compareType]);

  const exportToExcel = () => {
    // 导出Excel逻辑
    alert('导出Excel功能');
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-primary">历史数据查询与对比</h2>
          <p className="text-muted-foreground">多维度历史数据对比分析</p>
        </div>
        <Button onClick={exportToExcel}>
          <Download className="w-4 h-4 mr-2" />
          导出Excel
        </Button>
      </div>

      {/* 查询条件 */}
      <Card className="p-6">
        <h3 className="mb-4">查询条件</h3>
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div>
            <label className="text-sm mb-2 block">对比类型</label>
            <Select value={compareType} onValueChange={setCompareType}>
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="year">年度对比</SelectItem>
                <SelectItem value="quarter">季度对比</SelectItem>
                <SelectItem value="month">月度对比</SelectItem>
              </SelectContent>
            </Select>
          </div>

          <div>
            <label className="text-sm mb-2 block">设备筛选</label>
            <Select value={selectedMachinery} onValueChange={setSelectedMachinery}>
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部设备</SelectItem>
                {machineryList.map(m => (
                  <SelectItem key={m.id} value={m.id}>
                    {m.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div>
            <label className="text-sm mb-2 block">指标选择</label>
            <Select value={selectedMetric} onValueChange={setSelectedMetric}>
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                {Object.entries(metricConfig).map(([key, config]) => (
                  <SelectItem key={key} value={key}>
                    {config.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div className="flex items-end">
            <Button className="w-full">
              <Calendar className="w-4 h-4 mr-2" />
              查询
            </Button>
          </div>
        </div>
      </Card>

      {/* 对比图表 */}
      <Card className="p-6">
        <div className="flex items-center justify-between mb-4">
          <h3>
            {compareType === 'year' ? '年度对比（2023年 vs 2024年）' : 
             compareType === 'quarter' ? '季度对比（第一季度 vs 第二季度）' : 
             '月度对比（上月 vs 本月）'}
          </h3>
          <div className="text-sm text-muted-foreground">
            当前指标: <span className="text-success">{metricConfig[selectedMetric as keyof typeof metricConfig].label}</span>
            {selectedMachinery !== 'all' && (
              <span className="ml-2">
                | 设备: <span className="text-success">
                  {machineryList.find(m => m.id === selectedMachinery)?.name || '已选择'}
                </span>
              </span>
            )}
          </div>
        </div>
        <ResponsiveContainer width="100%" height={400}>
          <LineChart data={currentData}>
            <CartesianGrid strokeDasharray="3 3" />
            <XAxis dataKey={chartConfig.xDataKey} />
            <YAxis 
              label={{ 
                value: metricConfig[selectedMetric as keyof typeof metricConfig].label, 
                angle: -90, 
                position: 'insideLeft' 
              }}
            />
            <Tooltip 
              formatter={(value: number) => [
                `${value} ${metricConfig[selectedMetric as keyof typeof metricConfig].unit}`,
                ''
              ]}
            />
            <Legend />
            <Line 
              type="monotone" 
              dataKey={chartConfig.line1Key} 
              stroke="#3b82f6" 
              strokeWidth={2} 
              name={chartConfig.line1Name}
            />
            <Line 
              type="monotone" 
              dataKey={chartConfig.line2Key} 
              stroke="#10b981" 
              strokeWidth={2} 
              name={chartConfig.line2Name}
            />
          </LineChart>
        </ResponsiveContainer>
      </Card>

      {/* 对比数据表 */}
      <Card className="p-6">
        <h3 className="mb-4">对比数据详情</h3>
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-muted">
              <tr>
                <th className="px-4 py-2 text-left text-sm">时间</th>
                <th className="px-4 py-2 text-right text-sm">{chartConfig.line1Name}</th>
                <th className="px-4 py-2 text-right text-sm">{chartConfig.line2Name}</th>
                <th className="px-4 py-2 text-right text-sm">增长率</th>
              </tr>
            </thead>
            <tbody>
              {currentData.map((row, index) => {
                const timeValue = row[chartConfig.xDataKey as keyof typeof row];
                const value1 = row[chartConfig.line1Key as keyof typeof row] as number;
                const value2 = row[chartConfig.line2Key as keyof typeof row] as number;
                const growthRate = ((value2 - value1) / value1 * 100).toFixed(1);
                const unit = metricConfig[selectedMetric as keyof typeof metricConfig].unit;
                
                return (
                  <tr key={index} className="border-t">
                    <td className="px-4 py-2 text-sm">{timeValue}</td>
                    <td className="px-4 py-2 text-sm text-right">{value1} {unit}</td>
                    <td className="px-4 py-2 text-sm text-right">{value2} {unit}</td>
                    <td className={`px-4 py-2 text-sm text-right ${
                      value2 > value1 ? 'text-success' : 'text-error'
                    }`}>
                      {growthRate}%
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </Card>

      {/* 功能说明 */}
      <Card className="p-6 bg-info-muted border-info">
        <h4 className="mb-3 text-muted-foreground">对比功能</h4>
        <ul className="space-y-2 text-sm text-muted-foreground">
          <li>• 支持年度、季度、月度等多时间维度对比</li>
          <li>• 可按设备、地块、驾驶员等维度筛选</li>
          <li>• 提供折线图、柱状图等多种可视化方式</li>
          <li>• 支持数据导出为Excel格式</li>
          <li>• 自动计算增长率和变化趋势</li>
        </ul>
      </Card>
    </div>
  );
}
