import { useEffect, useState } from 'react';
import { PageParseAPI } from '../services/api';
import type { TelemetryData } from '../services/api';
import { Cpu, HardDrive, Activity } from 'lucide-react';

interface TelemetryPanelProps {
  isProcessing: boolean;
}

export const TelemetryPanel = ({ isProcessing }: TelemetryPanelProps) => {
  const [data, setData] = useState<TelemetryData>({
    cpu_percent: 0, ram_used_mb: 0, ram_total_mb: 8192, active_tasks: 0,
  });

  useEffect(() => {
    const fetchTelemetry = async () => {
      const telemetry = await PageParseAPI.getTelemetry(isProcessing);
      setData(telemetry);
    };
    fetchTelemetry();
    const interval = setInterval(fetchTelemetry, 1500);
    return () => clearInterval(interval);
  }, [isProcessing]);

  const ramPercent = Math.min(100, Math.round((data.ram_used_mb / data.ram_total_mb) * 100));
  const cpuColor = data.cpu_percent > 70 ? 'var(--danger)' : data.cpu_percent > 30 ? 'var(--warning)' : 'var(--accent)';
  const ramColor = ramPercent > 70 ? 'var(--danger)' : ramPercent > 50 ? 'var(--warning)' : 'var(--accent)';

  return (
    <div className="section">
      <div className="section-header">
        <h3><Activity size={16} className="text-secondary" /> System Telemetry</h3>
        {isProcessing && <span className="text-xs" style={{ color: 'var(--purple)' }}>Inference Active</span>}
      </div>
      <div className="section-body">
        <div className="telemetry-grid">
          <div className="telemetry-card">
            <div className="telemetry-label">
              <Cpu size={14} style={{ color: 'var(--purple)' }} />
              CPU Load
            </div>
            <div className="telemetry-value" style={{ color: cpuColor }}>{data.cpu_percent}%</div>
            <div className="telemetry-sub">On-device inference</div>
            <div className="telemetry-bar">
              <div className="telemetry-fill" style={{ width: `${data.cpu_percent}%`, background: cpuColor }} />
            </div>
          </div>
          <div className="telemetry-card">
            <div className="telemetry-label">
              <HardDrive size={14} style={{ color: 'var(--accent)' }} />
              Memory
            </div>
            <div className="telemetry-value" style={{ color: ramColor }}>{(data.ram_used_mb / 1024).toFixed(1)} GB</div>
            <div className="telemetry-sub">of {(data.ram_total_mb / 1024).toFixed(0)} GB used</div>
            <div className="telemetry-bar">
              <div className="telemetry-fill" style={{ width: `${ramPercent}%`, background: ramColor }} />
            </div>
          </div>
        </div>
        <div className={`telemetry-status ${isProcessing ? 'active' : ''}`}>
          {isProcessing ? (
            <><Cpu size={14} className="animate-spin" /> ONNX Runtime (CPU) + llama.cpp</>
          ) : (
            <><Cpu size={14} /> Models loaded in RAM (idle)</>
          )}
        </div>
      </div>
    </div>
  );
};
