import { useState, useEffect } from 'react';
import { Card } from '../../ui/card';
import { Badge } from '../../ui/badge';
import { Progress } from '../../ui/progress';
import { MachineryRecord } from '../../../types/machinery';
import { MachineryWorkState, WorkState } from '../../../types/equipment';
import { machineryStorage } from '../../../lib/machineryStorage';
import { Activity, Zap, Gauge, Droplet, Power } from 'lucide-react';

export function WorkStatus() {
  const [machinery, setMachinery] = useState<MachineryRecord[]>([]);
  const [workStates, setWorkStates] = useState<MachineryWorkState[]>([]);

  useEffect(() => {
    loadData();
    // 模拟实时更新
    const interval = setInterval(() => {
      updateStates();
    }, 3000);
    return () => clearInterval(interval);
  }, []);

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

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

  const getRandomState = (): WorkState => {
    const states: WorkState[] = ['熄火', '行驶中', '作业中', '待机'];
    const weights = [0.1, 0.3, 0.4, 0.2];
    const random = Math.random();
    let sum = 0;
    for (let i = 0; i < weights.length; i++) {
      sum += weights[i];
      if (random < sum) return states[i];
    }
    return '待机';
  };

  const updateStates = () => {
    setWorkStates(prev => prev.map(state => {
      // 模拟状态变化
      let newState = state.state;
      if (Math.random() > 0.9) {
        newState = getRandomState();
      }

      return {
        ...state,
        state: newState,
        speed: Math.max(0, state.speed + (Math.random() - 0.5) * 5),
        engineRpm: state.ignition ? 1000 + Math.random() * 2000 : 0,
        fuelLevel: Math.max(0, state.fuelLevel - Math.random() * 0.5),
        workingArea: state.state === '作业中' ? (state.workingArea || 0) + Math.random() * 0.5 : state.workingArea,
        timestamp: new Date().toISOString(),
      };
    }));
  };

  const getStateColor = (state: WorkState) => {
    switch (state) {
      case '作业中': return 'bg-success-muted text-success';
      case '行驶中': return 'bg-info-muted text-info';
      case '待机': return 'bg-warning-muted text-warning';
      case '熄火': return 'bg-muted text-muted-foreground';
      case '故障': return 'bg-error-muted text-error';
      default: return 'bg-muted text-muted-foreground';
    }
  };

  const getStateIcon = (state: WorkState) => {
    switch (state) {
      case '作业中': return Activity;
      case '行驶中': return Gauge;
      case '待机': return Power;
      default: return Activity;
    }
  };

  const stats = {
    total: workStates.length,
    working: workStates.filter(s => s.state === '作业中').length,
    moving: workStates.filter(s => s.state === '行驶中').length,
    idle: workStates.filter(s => s.state === '待机').length,
    offline: workStates.filter(s => s.state === '熄火').length,
  };

  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>

      {/* 统计卡片 */}
      <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">在线设备</div>
          <div className="mt-1">{stats.total}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">作业中</div>
          <div className="mt-1 text-success">{stats.working}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">行驶中</div>
          <div className="mt-1 text-info">{stats.moving}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">待机</div>
          <div className="mt-1 text-warning">{stats.idle}</div>
        </Card>
        <Card className="p-4">
          <div className="text-sm text-muted-foreground">离线</div>
          <div className="mt-1 text-gray-600">{stats.offline}</div>
        </Card>
      </div>

      {/* 设备状态列表 */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        {workStates.map(state => {
          const m = machinery.find(item => item.id === state.machineryId);
          if (!m) return null;

          const StateIcon = getStateIcon(state.state);

          return (
            <Card key={state.machineryId} className="p-6">
              <div className="flex items-start justify-between mb-4">
                <div className="flex items-center gap-3">
                  <div className={`p-2 rounded-lg ${state.state === '作业中' ? 'bg-success-muted' : state.state === '行驶中' ? 'bg-info-muted' : 'bg-muted'}`}>
                    <StateIcon className={`w-5 h-5 ${state.state === '作业中' ? 'text-success' : state.state === '行驶中' ? 'text-info' : 'text-muted-foreground'}`} />
                  </div>
                  <div>
                    <h3 className="text-base">{m.name}</h3>
                    <p className="text-xs text-muted-foreground">{m.model}</p>
                  </div>
                </div>
                <Badge variant="secondary" className={getStateColor(state.state)}>
                  {state.state}
                </Badge>
              </div>

              {/* 工况参数 */}
              <div className="space-y-3">
                <div className="grid grid-cols-2 gap-3">
                  <div className="flex items-center gap-2">
                    <Zap className="w-4 h-4 text-muted-foreground" />
                    <div className="flex-1">
                      <div className="text-xs text-muted-foreground">点火状态</div>
                      <div className="text-sm mt-0.5">
                        {state.ignition ? (
                          <span className="text-success">已启动</span>
                        ) : (
                          <span className="text-muted-foreground">已熄火</span>
                        )}
                      </div>
                    </div>
                  </div>

                  <div className="flex items-center gap-2">
                    <Gauge className="w-4 h-4 text-muted-foreground" />
                    <div className="flex-1">
                      <div className="text-xs text-muted-foreground">行驶速度</div>
                      <div className="text-sm mt-0.5">{state.speed.toFixed(1)} km/h</div>
                    </div>
                  </div>

                  <div className="flex items-center gap-2">
                    <Activity className="w-4 h-4 text-muted-foreground" />
                    <div className="flex-1">
                      <div className="text-xs text-muted-foreground">发动机转速</div>
                      <div className="text-sm mt-0.5">{state.engineRpm?.toFixed(0) || 0} RPM</div>
                    </div>
                  </div>

                  <div className="flex items-center gap-2">
                    <Power className="w-4 h-4 text-muted-foreground" />
                    <div className="flex-1">
                      <div className="text-xs text-muted-foreground">PTO状态</div>
                      <div className="text-sm mt-0.5">
                        {state.ptoStatus ? (
                          <span className="text-green-600">开启</span>
                        ) : (
                          <span className="text-gray-600">关闭</span>
                        )}
                      </div>
                    </div>
                  </div>
                </div>

                {/* 油量 */}
                <div>
                  <div className="flex items-center justify-between mb-2">
                    <div className="flex items-center gap-2">
                      <Droplet className="w-4 h-4 text-muted-foreground" />
                      <span className="text-xs text-muted-foreground">油量</span>
                    </div>
                    <span className="text-sm">{state.fuelLevel?.toFixed(0) || 0}%</span>
                  </div>
                  <Progress value={state.fuelLevel || 0} className="h-2" />
                </div>

                {/* 作业数据 */}
                {state.state === '作业中' && (
                  <div className="pt-3 border-t">
                    <div className="grid grid-cols-2 gap-3">
                      <div>
                        <div className="text-xs text-muted-foreground">作业面积</div>
                        <div className="text-sm mt-0.5">{state.workingArea?.toFixed(1) || 0} 亩</div>
                      </div>
                      <div>
                        <div className="text-xs text-muted-foreground">作业速率</div>
                        <div className="text-sm mt-0.5">{state.workingRate?.toFixed(1) || 0} 亩/时</div>
                      </div>
                    </div>
                  </div>
                )}
              </div>

              <div className="mt-4 pt-3 border-t text-xs text-muted-foreground">
                更新时间: {new Date(state.timestamp).toLocaleTimeString('zh-CN')}
              </div>
            </Card>
          );
        })}
      </div>

      {/* 状态说明 */}
      <Card className="p-6 bg-blue-50 border-blue-200">
        <h4 className="mb-3 text-blue-900">状态判断规则</h4>
        <ul className="space-y-2 text-sm text-blue-800">
          <li>• <strong>熄火</strong>: 点火信号=关闭</li>
          <li>• <strong>待机</strong>: 点火信号=开启，速度=0，PTO=关闭</li>
          <li>• <strong>行驶中</strong>: 点火信号=开启，速度&gt;0，PTO=关闭</li>
          <li>• <strong>作业中</strong>: 点火信号=开启，PTO=开启（或速度&gt;0且在作业区域）</li>
          <li>• <strong>故障</strong>: 检测到故障码或异常传感器数据</li>
        </ul>
      </Card>
    </div>
  );
}
