import moment from 'moment'
import { DatePicker } from 'antd'
import { useState, useEffect } from 'react'
import { useParams } from 'react-router-dom'

import LoaderPortal from '@components/LoaderPortal'
import { invokeWebApiWrapperAsync } from '@components/factory'
import { TelemetryAnalyticsService } from '@api'
import { ChartOperationTime } from './charts/ChartOperationTime'

const { RangePicker } = DatePicker

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

export const AnalysisOperationTime = () => {
  const { id } = useParams()
  const [operationTimeData, setOperationTimeData] = useState([])
  const [loader, setLoader] = useState(false)
  const [range, setRange] = useState([moment().subtract(1,'days'), moment()])

  useEffect(() => invokeWebApiWrapperAsync(
    async () => {
      const begin = range?.length > 1 ? range[0].toISOString() : null
      const end = range?.length > 1 ? range[1].toISOString() : null
      const summary = await TelemetryAnalyticsService.getOperationsSummary(id, begin, end)
      setOperationTimeData(summary)
    },
    setLoader,
    `Не удалось получить данные для Анализа Операция-Время по скважине '${id}' за период с ${begin} по ${end}`
  ), [id, range])

  return (
    <LoaderPortal show={loader}>
      <RangePicker showTime onChange={(range) => setRange(range)} />
      <ChartOperationTime data={operationTimeData} lines={lines} />
    </LoaderPortal>
  )
}

export default AnalysisOperationTime
