import { useState, useEffect, useRef } from 'react';
import DroneMonitorGauge from './DroneMonitorGauge';

interface DroneMonitorProps {
  visible: boolean;
}

function generateWave(base: number, variance: number, length: number): number[] {
  const wave: number[] = [];
  for (let i = 0; i < length; i++) {
    wave.push(base + Math.sin(i * 0.1) * variance + (Math.random() - 0.5) * variance * 0.5);
  }
  return wave;
}

export default function DroneMonitor({ visible }: DroneMonitorProps) {
  const [cpuData, setCpuData] = useState<number[]>(() => generateWave(35, 20, 60));
  const [netData, setNetData] = useState<number[]>(() => generateWave(20, 15, 60));
  const [ioData, setIoData] = useState<number[]>(() => generateWave(10, 10, 60));
  const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);

  useEffect(() => {
    if (!visible) {
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
        intervalRef.current = null;
      }
      return;
    }

    intervalRef.current = setInterval(() => {
      setCpuData((prev) => {
        const next = [...prev.slice(1), Math.max(0, Math.min(100, prev[prev.length - 1]! + (Math.random() - 0.5) * 10))];
        return next;
      });
      setNetData((prev) => {
        const next = [...prev.slice(1), Math.max(0, Math.min(100, prev[prev.length - 1]! + (Math.random() - 0.5) * 8))];
        return next;
      });
      setIoData((prev) => {
        const next = [...prev.slice(1), Math.max(0, Math.min(100, prev[prev.length - 1]! + (Math.random() - 0.5) * 6))];
        return next;
      });
    }, 200);

    return () => {
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
        intervalRef.current = null;
      }
    };
  }, [visible]);

  return (
    <div className="bg-bg-secondary border border-border-default rounded overflow-hidden">
      <div className="p-2 border-b border-border-subtle bg-bg-tertiary">
        <h3 className="text-xs font-semibold text-text-secondary uppercase tracking-wider">
          Resource Monitor
        </h3>
      </div>
      <div className="flex gap-1 p-1 justify-center">
        <DroneMonitorGauge
          label="CPU"
          data={cpuData}
          unit="%"
          color="#c20600"
        />
        <DroneMonitorGauge
          label="NETWORK"
          data={netData}
          unit="%"
          color="#06b6d4"
        />
        <DroneMonitorGauge
          label="FILE I/O"
          data={ioData}
          unit="%"
          color="#22c55e"
        />
      </div>
    </div>
  );
}
