import { useParams } from "react-router-dom"
import { DatePicker, ConfigProvider } from 'antd';
import notify from "../components/notify"
import { useState, useEffect } from 'react'
import { AnalyticsService } from '../services/api'
import { ChartOperationTime } from './charts/ChartOperationTime'
import locale from "antd/lib/locale/ru_RU";

const { RangePicker } = DatePicker

const lines = [{ labelAccessorName: "processName", pieceAccessorName: "duration" }]

export function AnalysisOperationTime() {
  let { id } = useParams()
  const [operationTimeData, setOperationTimeData] = useState([])
  const [loader, setLoader] = useState(false)
  const [range, setRange] = useState([])

  let begin = null
  let end = null

  const onChangeRange = (range) => {
    setRange(range)
  }

  const handleReceiveOperationTimeData = (data) => {
    setOperationTimeData(data)
  }

  useEffect(() => {
    setLoader(true)
    if (range?.length > 1) {
      begin = range[0].toISOString()
      end = range[1].toISOString()
    }
    AnalyticsService.getOperationsSummary(id, begin, end)
      .then(handleReceiveOperationTimeData)
      .catch(error => {
        notify(`Не удалось получить данные для Анализа Операция-Время по скважине "${id}" за период с ${begin} по ${end}`,
          'warning')
        console.log(error)
      })
      .finally(setLoader(false))
  }, [id, range])

  return (
    <>
      <ConfigProvider locale={locale}>
        <RangePicker
          showTime
          onChange={onChangeRange}
        />
      </ConfigProvider>
      <ChartOperationTime
        data={operationTimeData}
        lines={lines}
      />
    </>
  )
}