import React, { useState, useEffect } from "react";
import { Card, Statistic, Row, Col, Divider, Tag } from "antd";
import { CarOutlined, RetweetOutlined, SwapOutlined } from "@ant-design/icons";

export default function DraggableSpeedDisplay({ 
  component,
  ws,
  connected
}) {
  const [speedData, setSpeedData] = useState({
    speed: "0.00",
    unit: "km/h",
    rpm: "0.00",
    direction: "停止",
    timestamp: Date.now()
  });

  useEffect(() => {
    if (!ws || !connected) return;

    const handleSpeedUpdate = (data) => {
      setSpeedData(prev => ({
        ...prev,
        ...data,
        timestamp: Date.now()
      }));
    };

    // 监听速度数据更新
    const handleMessage = (event) => {
      try {
        const message = JSON.parse(event.data);
        if (message.action === 'encoder-data' || message.type === 'encoder-data') {
          handleSpeedUpdate(message.payload || message.data);
        }
      } catch (e) {
        // 忽略非JSON消息
      }
    };

    ws.addEventListener('message', handleMessage);

    return () => {
      ws.removeEventListener('message', handleMessage);
    };
  }, [ws, connected]);

  // 计算最后一次更新的时间
  const timeDiff = Date.now() - speedData.timestamp;
  const isStale = timeDiff > 3000; // 3秒后认为数据过时

  const config = component.config || {};
  const showRpm = config.showRpm !== false; // 默认显示
  const showDirection = config.showDirection !== false; // 默认显示
  const speedLabel = config.speedLabel || "车速";
  const rpmLabel = config.rpmLabel || "转速";
  const directionLabel = config.directionLabel || "方向";

  return (
    <Card 
      title={component.name || "车速显示"} 
      size="small"
      style={{ 
        background: isStale ? '#f0f0f0' : '#ffffff',
        opacity: isStale ? 0.7 : 1
      }}
    >
      <div style={{ padding: '8px 0' }}>
        <div style={{ marginBottom: '8px' }}>
          <Statistic
            title={
              <span style={{ fontSize: '12px' }}>
                <CarOutlined style={{ marginRight: '4px', color: '#1890ff' }} />
                {speedLabel}
              </span>
            }
            value={speedData.speed}
            precision={2}
            valueStyle={{ 
              color: '#3f8600', 
              fontSize: '16px',
              fontWeight: 'bold'
            }}
            prefix=""
            suffix={speedData.unit || "km/h"}
          />
        </div>
        
        {showRpm && (
          <div style={{ marginBottom: '8px' }}>
            <Statistic
              title={
                <span style={{ fontSize: '12px' }}>
                  <RetweetOutlined style={{ marginRight: '4px', color: '#52c41a' }} />
                  {rpmLabel}
                </span>
              }
              value={speedData.rpm}
              precision={2}
              valueStyle={{ 
                color: '#1890ff', 
                fontSize: '14px'
              }}
              prefix=""
              suffix="RPM"
            />
          </div>
        )}
        
        {showDirection && (
          <div>
            <div style={{
              display: 'flex',
              alignItems: 'center'
            }}>
              <SwapOutlined style={{ marginRight: '4px', color: '#52c41a' }} />
              <span style={{ fontSize: '12px', color: '#52c41a', fontWeight: 'bold' }}>
                {directionLabel}: {speedData.direction}
              </span>
            </div>
          </div>
        )}
        
        <div style={{
          marginTop: '8px',
          fontSize: '10px',
          color: '#888',
          textAlign: 'right'
        }}>
          {isStale ? '数据已停止更新' : '实时'}
        </div>
      </div>
    </Card>
  );
}