import { useState, useEffect } from 'react';
import {CaretUpOutlined, CaretDownOutlined} from '@ant-design/icons'

export const ValueDisplay = ({prefix, value, suffix, isArrowVisible}) =>{
  const [oldVal, setOldVal] = useState(NaN)
  const [val, setVal] = useState('---')
  const [arrowState, setArrowState] = useState(0)

  useEffect(()=>{
    if(value){
      if(Number.isFinite(+value)){
        if (isArrowVisible)
        {
          let newArrowState = 0
          if (value > oldVal)
            newArrowState = 1
          if (value < oldVal)
            newArrowState = -1
          setArrowState(newArrowState)
          setOldVal(value)
        }
        setVal((+value).toPrecision(4)??'---')
      }
      else
        setVal(value)
    }

  },[value, isArrowVisible, oldVal])

  let arrow = null
  switch  (arrowState){
    case 1:
      arrow = <CaretUpOutlined style={{color:"red"}}/>
      break
    case -1:
      arrow = <CaretDownOutlined style={{color:"red"}}/>
      break
    default:
      break
  } 

  return(<span className='display_value'>{prefix} {val} {suffix}{arrow}</span>)
}

export const Display = (props)=>{
  const {label} = props

  return <div className={props.className}>
      <div className='display_label'>{label}</div>        
      <div style={{display:"flex", flexGrow:1}}>
        <ValueDisplay {...props}/>
      </div>
    </div>
  
}