import { useRef, useLayoutEffect, useState, useEffect } from 'react'
import {
  Button,
  DatePicker,
  ConfigProvider,
  Row,
  Col,
  Tooltip} from 'antd'
import { useParams } from 'react-router-dom'
import { DataService } from '../services/api'
import locale from 'antd/lib/locale/ru_RU'
import {generateUUID} from '../services/UidGenerator'
import { ArchiveColumn } from '../components/ArchiveColumn'
import moment from 'moment'
import notify from '../components/notify'
import LoaderPortal from '../components/LoaderPortal'

const { RangePicker } = DatePicker

const SaveObject = (key, obj) => {
  let json = JSON.stringify(obj)
  localStorage.setItem(key, json)
}

const LoadObject = (key) => {
  let json = localStorage.getItem(key)
  return json ? JSON.parse(json) : null  
}

export default function Archive() {
  let { id } = useParams();
  const [saubData, setSaubData] = useState([])
  const [chartsCfgs, setChartsCfgs] = useState([])
  const [rangeDate, setRangeDate] = useState([moment().subtract(3,'hours'), moment()])
  const [geometry, setGeometry] = useState({ratioRest:1, ratio1st:1, wRest:.5, w1st:.5})  
  const [loader, setLoader] = useState(false)
  const chartsCfgsKey = 'chartsCfgs'
  const chartsContainerRef = useRef();

  const handleReceiveDataSaub = (data) => {
    if (data)
      setSaubData(data)
  }
  
  const onAddChart = () => {
    let newChartCfgs = [...chartsCfgs, {id: generateUUID(), yDisplay: false, aspectRatio:1}]
    setChartsCfgs(newChartCfgs)
  }

  const onRemoveChart = (id) => {
    let newChartCfgs = chartsCfgs.filter(cfg => cfg.id !== id )
    setChartsCfgs(newChartCfgs)
  }

  const onSaveConfig = ()=>{    
    SaveObject(chartsCfgsKey, chartsCfgs)
  }

  const onChangeRange = (range) => {
    setRangeDate(range)
  }
  
  useLayoutEffect(()=>{
    if(chartsContainerRef.current && chartsCfgs?.length){
      let w = chartsContainerRef.current.offsetWidth //1792
      w = w > 0 ? w : 1792
      let ot = chartsContainerRef.current.offsetTop
      let ph = chartsContainerRef.current.offsetParent.offsetHeight
      let h = ph - ot - 32 //761      
      h = h > 0 ? h : 761

      let chartsCount = chartsCfgs.length

      let labelLenght = 8
      let borderWidth = 8
      let wRest = Math.floor((w - labelLenght)/chartsCount) - borderWidth
      let w1st = wRest + labelLenght

      let ratio1st = w1st/h
      let ratioRest = wRest/h

      setGeometry({ratio1st, ratioRest, w1st, wRest})
    }
  },[chartsContainerRef, chartsCfgs])

  useEffect(() => {    
    let cfgs = LoadObject(chartsCfgsKey)
    if(cfgs)
      setChartsCfgs(cfgs)
  },[])

  useEffect(()=>{
    SaveObject(chartsCfgsKey, chartsCfgs)
  },[chartsCfgs])

  useEffect(() => {
    let interval = (rangeDate[1] - rangeDate[0]) / 1000
    let startDate = rangeDate[0].toISOString()
    
    setLoader(true)
    DataService.getData(id, startDate, interval, 2048)
      .then(handleReceiveDataSaub)
      .catch(error => {
        notify(`Не удалось загрузить данные по скважине (${id}) c ${rangeDate[0]} по ${rangeDate[1]}`, 'error')
        console.error(error)
      })
      .finally(()=>setLoader(false))
  }, [id, rangeDate]);

  let charts = null
  if(chartsCfgs.length > 0){
    chartsCfgs[0].yDisplay = true
  
    charts = chartsCfgs.map((cfg, i) =>
    <Col flex={`${i===0 ? geometry.w1st : geometry.wRest}px`}
      key={cfg.id}>
      <ArchiveColumn
        data={saubData}
        rangeDate={rangeDate}
        chartRatio={i===0 ? geometry.ratio1st : geometry.ratioRest}
        onRemoveChart={onRemoveChart} 
        onSaveConfig={onSaveConfig}
        config={cfg}/>
    </Col>)
  }

  return (<>
    <Tooltip title="Добавить график">
      <Button 
        type="primary"
        onClick={onAddChart}
        disabled={chartsCfgs.length >= 6}>
        +
      </Button>
    </Tooltip>
    <ConfigProvider locale={locale}>
      <RangePicker
        showTime
        allowClear={false}
        onChange = {onChangeRange}
        value = {rangeDate}
        />
    </ConfigProvider>
    <LoaderPortal show={loader}>
      <Row ref={chartsContainerRef}>
          {charts}
      </Row>
    </LoaderPortal>
  </>)
}