import { useState, useEffect } from 'react';
import { Card } from '../../ui/card';
import { MachineryRecord } from '../../../types/machinery';
import { MachineryWorkState } from '../../../types/equipment';
import { machineryStorage } from '../../../lib/machineryStorage';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, LineChart, Line, PieChart, Pie, Cell } from 'recharts';
import { TrendingUp, Target, Zap, MapPin, Calendar } from 'lucide-react';
import { Tabs, TabsList, TabsTrigger } from '../../ui/tabs';

// 时间范围类型
type TimeRange = 'day' | 'month' | 'year';

export function OperationData() {
  const [machinery, setMachinery] = useState<MachineryRecord[]>([]);
  const [workStates, setWorkStates] = useState<MachineryWorkState[]>([]);
  const [historyData, setHistoryData] = useState<any[]>([]);
  const [timeRange, setTimeRange] = useState<TimeRange>('month'); // 默认近30天

  useEffect(() => {
    loadData();
    const interval = setInterval(() => {
      updateData();
    }, 5000);
    return () => clearInterval(interval);
  }, []);

  useEffect(() => {
    // 时间范围改变时重新生成历史数据
    generateHistoryData(timeRange);
  }, [timeRange]);

  const loadData = () => {
    const machineryData = machineryStorage.getAllMachinery();
    setMachinery(machineryData);

    // 初始化模拟工作状态
    const mockStates: MachineryWorkState[] = machineryData.slice(0, 4).map(m => ({
      machineryId: m.id,
      state: '作业中',
      ignition: true,
      speed: 10 + Math.random() * 20,
      ptoStatus: true,
      engineRpm: 1500 + Math.random() * 1000,
      fuelLevel: 50 + Math.random() * 40,
      workingArea: 10 + Math.random() * 40,
      workingRate: 5 + Math.random() * 10,
      timestamp: new Date().toISOString(),
    }));
    setWorkStates(mockStates);

    // 生成初始历史数据（默认近30天）
    generateHistoryData('month');
  };

  const generateHistoryData = (range: TimeRange) => {
    const history = [];
    const now = new Date();
    let dataPoints = 0;
    let timeUnit = '';
    let increment = 0;

    switch (range) {
      case 'day':
        // 当天：24小时数据，每小时一个点
        dataPoints = 24;
        timeUnit = 'hour';
        increment = 60 * 60 * 1000; // 1小时
        for (let i = dataPoints - 1; i >= 0; i--) {
          const time = new Date(now.getTime() - i * increment);
          history.push({
            time: time.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }),
            fullTime: time,
            area: 2 + Math.random() * 5,
            rate: 5 + Math.random() * 5,
            efficiency: 70 + Math.random() * 25,
          });
        }
        break;

      case 'month':
        // 近30天：30个数据点，每天一个点
        dataPoints = 30;
        timeUnit = 'day';
        increment = 24 * 60 * 60 * 1000; // 1天
        for (let i = dataPoints - 1; i >= 0; i--) {
          const time = new Date(now.getTime() - i * increment);
          history.push({
            time: `${time.getMonth() + 1}/${time.getDate()}`,
            fullTime: time,
            area: 20 + Math.random() * 30,
            rate: 5 + Math.random() * 8,
            efficiency: 70 + Math.random() * 25,
          });
        }
        break;

      case 'year':
        // 当年：12个月数据，每月一个点
        dataPoints = 12;
        timeUnit = 'month';
        const currentMonth = now.getMonth();
        for (let i = 0; i < dataPoints; i++) {
          const monthIndex = (currentMonth - dataPoints + 1 + i + 12) % 12;
          const monthNames = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
          history.push({
            time: monthNames[monthIndex],
            fullTime: new Date(now.getFullYear(), monthIndex, 1),
            area: 200 + Math.random() * 300,
            rate: 6 + Math.random() * 4,
            efficiency: 75 + Math.random() * 20,
          });
        }
        break;
    }

    setHistoryData(history);
  };

  const updateData = () => {
    setWorkStates(prev => prev.map(state => ({
      ...state,
      workingArea: (state.workingArea || 0) + Math.random() * 0.5,
      workingRate: 5 + Math.random() * 10,
      speed: 10 + Math.random() * 20,
      timestamp: new Date().toISOString(),
    })));

    // 只在"天"模式下实时更新图表
    if (timeRange === 'day') {
      setHistoryData(prev => {
        const newData = [...prev.slice(1)];
        const lastArea = prev[prev.length - 1]?.area || 0;
        newData.push({
          time: new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }),
          fullTime: new Date(),
          area: lastArea + Math.random() * 2,
          rate: 5 + Math.random() * 5,
          efficiency: 70 + Math.random() * 25,
        });
        return newData;
      });
    }
  };

  const totalArea = workStates.reduce((sum, s) => sum + (s.workingArea || 0), 0);
  const avgRate = workStates.reduce((sum, s) => sum + (s.workingRate || 0), 0) / (workStates.length || 1);

  // 根据时间范围计算总计数据
  const calculateTotals = () => {
    const totalHistoryArea = historyData.reduce((sum, d) => sum + d.area, 0);
    const avgHistoryRate = historyData.reduce((sum, d) => sum + d.rate, 0) / (historyData.length || 1);
    const avgEfficiency = historyData.reduce((sum, d) => sum + d.efficiency, 0) / (historyData.length || 1);
    
    return {
      totalArea: totalHistoryArea,
      avgRate: avgHistoryRate,
      avgEfficiency: avgEfficiency,
    };
  };

  const totals = calculateTotals();

  // 时间范围标签
  const getTimeRangeLabel = () => {
    switch (timeRange) {
      case 'day':
        return '今日';
      case 'month':
        return '近30天';
      case 'year':
        return '本年度';
    }
  };

  // 生成作业类型分布数据（示例）
  const operationTypeData = [
    { name: '耕地', value: 35, color: '#10b981' },
    { name: '播种', value: 25, color: '#3b82f6' },
    { name: '施肥', value: 20, color: '#f59e0b' },
    { name: '收割', value: 20, color: '#8b5cf6' },
  ];

  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>
        
        {/* 时间范围切换 */}
        <div className="flex items-center gap-2">
          <Calendar className="w-4 h-4 text-muted-foreground" />
          <Tabs value={timeRange} onValueChange={(value) => setTimeRange(value as TimeRange)}>
            <TabsList>
              <TabsTrigger value="day">天</TabsTrigger>
              <TabsTrigger value="month">近30天</TabsTrigger>
              <TabsTrigger value="year">年</TabsTrigger>
            </TabsList>
          </Tabs>
        </div>
      </div>

      {/* 统计卡片 - 根据时间范围显示不同数据 */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <Card className="p-4">
          <div className="flex items-center gap-3">
            <div className="p-2 rounded-lg bg-success-muted">
              <MapPin className="w-5 h-5 text-success" />
            </div>
            <div>
              <div className="text-xs text-muted-foreground">{getTimeRangeLabel()}作业面积</div>
              <div className="mt-1">{totals.totalArea.toFixed(1)} 亩</div>
            </div>
          </div>
        </Card>
        <Card className="p-4">
          <div className="flex items-center gap-3">
            <div className="p-2 rounded-lg bg-info-muted">
              <TrendingUp className="w-5 h-5 text-info" />
            </div>
            <div>
              <div className="text-xs text-muted-foreground">平均速率</div>
              <div className="mt-1">{totals.avgRate.toFixed(1)} 亩/时</div>
            </div>
          </div>
        </Card>
        <Card className="p-4">
          <div className="flex items-center gap-3">
            <div className="p-2 rounded-lg bg-info-muted">
              <Target className="w-5 h-5 text-info" />
            </div>
            <div>
              <div className="text-xs text-muted-foreground">作业效率</div>
              <div className="mt-1">{totals.avgEfficiency.toFixed(1)}%</div>
            </div>
          </div>
        </Card>
        <Card className="p-4">
          <div className="flex items-center gap-3">
            <div className="p-2 rounded-lg bg-warning-muted">
              <Zap className="w-5 h-5 text-warning" />
            </div>
            <div>
              <div className="text-xs text-muted-foreground">作业设备</div>
              <div className="mt-1">{workStates.length} 台</div>
            </div>
          </div>
        </Card>
      </div>

      {/* 作业趋势图表 */}
      <Card className="p-6">
        <h3 className="mb-4">
          作业趋势 <span className="text-sm text-muted-foreground ml-2">({getTimeRangeLabel()})</span>
        </h3>
        <ResponsiveContainer width="100%" height={300}>
          <LineChart data={historyData}>
            <CartesianGrid strokeDasharray="3 3" />
            <XAxis dataKey="time" />
            <YAxis yAxisId="left" />
            <YAxis yAxisId="right" orientation="right" />
            <Tooltip />
            <Legend />
            <Line
              yAxisId="left"
              type="monotone"
              dataKey="area"
              stroke="#10b981"
              strokeWidth={2}
              name={`作业面积 (亩${timeRange === 'day' ? '/时' : timeRange === 'month' ? '/天' : '/月'})`}
            />
            <Line
              yAxisId="right"
              type="monotone"
              dataKey="rate"
              stroke="#3b82f6"
              strokeWidth={2}
              name="作业速率 (亩/时)"
            />
          </LineChart>
        </ResponsiveContainer>
      </Card>

      {/* 双图表行 */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        {/* 设备作业对比 */}
        <Card className="p-6">
          <h3 className="mb-4">设备作业对比 <span className="text-sm text-muted-foreground ml-2">(实时)</span></h3>
          <ResponsiveContainer width="100%" height={300}>
            <BarChart data={workStates.map(state => {
              const m = machinery.find(item => item.id === state.machineryId);
              return {
                name: m?.name || '未知',
                area: state.workingArea || 0,
                rate: state.workingRate || 0,
              };
            })}>
              <CartesianGrid strokeDasharray="3 3" />
              <XAxis dataKey="name" />
              <YAxis yAxisId="left" />
              <YAxis yAxisId="right" orientation="right" />
              <Tooltip />
              <Legend />
              <Bar yAxisId="left" dataKey="area" fill="#10b981" name="作业面积 (亩)" />
              <Bar yAxisId="right" dataKey="rate" fill="#3b82f6" name="作业速率 (亩/时)" />
            </BarChart>
          </ResponsiveContainer>
        </Card>

        {/* 作业类型分布 */}
        <Card className="p-6">
          <h3 className="mb-4">作业类型分布 <span className="text-sm text-muted-foreground ml-2">({getTimeRangeLabel()})</span></h3>
          <ResponsiveContainer width="100%" height={300}>
            <PieChart>
              <Pie
                data={operationTypeData}
                cx="50%"
                cy="50%"
                labelLine={false}
                label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}
                outerRadius={80}
                fill="#8884d8"
                dataKey="value"
              >
                {operationTypeData.map((entry, index) => (
                  <Cell key={`cell-${index}`} fill={entry.color} />
                ))}
              </Pie>
              <Tooltip />
            </PieChart>
          </ResponsiveContainer>
        </Card>
      </div>

      {/* 效率趋势图表 */}
      <Card className="p-6">
        <h3 className="mb-4">
          作业效率趋势 <span className="text-sm text-muted-foreground ml-2">({getTimeRangeLabel()})</span>
        </h3>
        <ResponsiveContainer width="100%" height={250}>
          <LineChart data={historyData}>
            <CartesianGrid strokeDasharray="3 3" />
            <XAxis dataKey="time" />
            <YAxis domain={[0, 100]} />
            <Tooltip />
            <Legend />
            <Line
              type="monotone"
              dataKey="efficiency"
              stroke="#8b5cf6"
              strokeWidth={2}
              name="作业效率 (%)"
            />
          </LineChart>
        </ResponsiveContainer>
      </Card>

      {/* 详细数据表 */}
      <Card className="p-6">
        <h3 className="mb-4">实时作业数据</h3>
        <div className="space-y-4">
          {workStates.map(state => {
            const m = machinery.find(item => item.id === state.machineryId);
            if (!m) return null;

            return (
              <div key={state.machineryId} className="p-4 border rounded-lg">
                <div className="flex items-center justify-between mb-3">
                  <div>
                    <h4 className="text-base">{m.name}</h4>
                    <p className="text-sm text-muted-foreground">{m.model}</p>
                  </div>
                  <div className="text-xs text-muted-foreground">
                    {new Date(state.timestamp).toLocaleTimeString('zh-CN')}
                  </div>
                </div>

                <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                  <div>
                    <div className="text-xs text-muted-foreground">作业面积</div>
                    <div className="mt-1">
                      <span className="text-lg text-success">{state.workingArea?.toFixed(1)}</span>
                      <span className="text-sm text-muted-foreground ml-1">亩</span>
                    </div>
                  </div>
                  <div>
                    <div className="text-xs text-muted-foreground">作业速率</div>
                    <div className="mt-1">
                      <span className="text-lg text-info">{state.workingRate?.toFixed(1)}</span>
                      <span className="text-sm text-muted-foreground ml-1">亩/时</span>
                    </div>
                  </div>
                  <div>
                    <div className="text-xs text-muted-foreground">行驶速度</div>
                    <div className="mt-1">
                      <span className="text-lg">{state.speed.toFixed(1)}</span>
                      <span className="text-sm text-muted-foreground ml-1">km/h</span>
                    </div>
                  </div>
                  <div>
                    <div className="text-xs text-muted-foreground">发动机转速</div>
                    <div className="mt-1">
                      <span className="text-lg">{state.engineRpm?.toFixed(0)}</span>
                      <span className="text-sm text-muted-foreground ml-1">RPM</span>
                    </div>
                  </div>
                </div>
              </div>
            );
          })}
        </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>• <strong>天</strong>: 显示当天24小时的作业数据，每小时一个数据点</li>
          <li>• <strong>近30天</strong>: 显示最近30天的作业数据，每天一个数据点（默认）</li>
          <li>• <strong>年</strong>: 显示本年度12个月的作业数据，每月一个数据点</li>
          <li>• 作业面积基于GPS轨迹和地块边界自动计算</li>
          <li>• 作业速率通过单位时间内的作业面积变化计算</li>
          <li>• 实时数据每5秒更新一次，历史数据根据所选时间范围展示</li>
        </ul>
      </Card>
    </div>
  );
}
