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

export const formatNumber = (value, format) => 
  Number.isInteger(format) && Number.isFinite(value)
  ? (+value).toFixed(format)
  : (+value).toPrecision(4)

export const ValueDisplay = ({prefix, value, suffix, isArrowVisible, format}) =>{
  const [val, setVal] = useState('---')
  const [arrowState, setArrowState] = useState({ 
    preVal: NaN,
    preTimestamp: Date.now(),
    direction: 0,
  })

  useEffect(()=>{
    if(value === undefined || value === null){
      setVal('---')
      return
    }

    if(Number.isFinite(+value)){
      if ((isArrowVisible) && (arrowState.preTimestamp + 1000 < Date.now()))
      {
        let direction = 0
        if (value > arrowState.preVal)
          direction = 1
        if (value < arrowState.preVal)
          direction = -1

        setArrowState({ 
          preVal: value,
          preTimestamp: Date.now(),
          direction: direction,
        })      
      }

      setVal(formatNumber(value, format))
      return
    }

    let valueDate = moment(value)
    if(valueDate.isValid()){
      setVal(valueDate.format(format))
      return
    }

    setVal(value)
  },[value, isArrowVisible, arrowState, format])

  let arrow = null
  if(isArrowVisible)
    switch  (arrowState.direction){
      case 0:
        arrow = <CaretRightOutlined style={{color:"#0008"}}/>
        break
      case 1:
        arrow = <CaretUpOutlined style={{color:"#0008"}}/>
        break
      case -1:
        arrow = <CaretDownOutlined style={{color:"#0008"}}/>
        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>
  
}