import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';

const JKLatencyBadge = ({ latencyData, showAll }) => {
  
  const LATENCY_SCORES = {
    good: { label: 'GOOD', min: 0, max: 40 },
    fair: { label: 'FAIR', min: 40, max: 60 },
    high: { label: 'HIGH', min: 60, max: 10000000 },
    me:   { label: 'ME', min: -1, max: -1 },
    unknown: { label: 'UNKNOWN', min: -2, max: -2 }
  };

  const [label, setLabel] = useState('UNKNOWN');
  const [latencyInfo, setLatencyInfo] = useState('');

  const setLatencyLabel = totalLatency => {
    let lbl;
    if (totalLatency >= LATENCY_SCORES['good']['min'] && totalLatency <= LATENCY_SCORES['good']['max']) {
      lbl = LATENCY_SCORES['good']['label'];
    } else if (totalLatency > LATENCY_SCORES['fair']['min'] && totalLatency <= LATENCY_SCORES['fair']['max']) {
      lbl = LATENCY_SCORES['fair']['label'];
    } else if (totalLatency > LATENCY_SCORES['fair']['min'] && totalLatency <= LATENCY_SCORES['fair']['max']) {
      lbl = LATENCY_SCORES['fair']['label'];
    } else if (totalLatency > LATENCY_SCORES['high']['min']) {
      lbl = LATENCY_SCORES['high']['label'];
    } else {
      lbl = LATENCY_SCORES['unknown']['label'];
    }
    setLabel(lbl);
  };

  useEffect(() => {
    if (latencyData) {
      const tot = Math.round(latencyData.ars_internet_latency) + Math.round(latencyData.audio_latency);
      setLatencyLabel(tot);

      if (showAll) {
        setLatencyInfo(`${Math.round(latencyData.ars_internet_latency)}ms (Internet) + ${Math.round(latencyData.audio_latency)}ms (audio) = ${tot}ms (total) `);
      } else {
        setLatencyInfo(`${tot}ms`);
      }
    }
  }, [latencyData]);

  return (
    <>
      {latencyInfo} <span className={`badge latency-badge latency-${label.toLowerCase()}`}>{label}</span>
    </>
  );
};

JKLatencyBadge.propTypes = {
  latencyData: PropTypes.object,
  showAll: PropTypes.bool
};

JKLatencyBadge.defaultProps = {
  showAll: false
};

export default JKLatencyBadge;
