import { useState, useEffect } from 'react'
import { useRouteMatch } from 'react-router-dom'
import { DepositService } from '../services/api'
import LoaderPortal from './LoaderPortal'
import { TreeSelect } from 'antd'
import { useHistory } from 'react-router-dom'
import { notify } from "./factory"
import '../styles/wellTreeSelect.css'

export default function WellTreeSelector() {
  const [wellsTree, setWellsTree] = useState([])
  const [showLoader, setShowLoader] = useState(false)
  const history = useHistory()
  const routeMatch = useRouteMatch('/:route/:id')

  const updateWellsList = async () => {
    setShowLoader(true)
    try {
      const deposits = await DepositService.getDeposits()
      const wellsTree = deposits.map(deposit =>({
        title: deposit.caption,
        key: `/deposit/${deposit.id}`,
        value: `/deposit/${deposit.id}`,
        children: deposit.clusters.map(cluster => ({
          title: cluster.caption,
          key: `/cluster/${cluster.id}`,
          value: `/cluster/${cluster.id}`,
          children: cluster.wells.map(well => ({
            title: well.caption,
            key: `/well/${well.id}`,
            value: `/well/${well.id}`,
          })),
        })),
      }))
      setWellsTree(wellsTree)
    }
    catch (e) {
      notify('Не удалось загрузить список скважин', 'error')
      console.error(`${e.message}`)
    }
    setShowLoader(false)
  }

  useEffect(() => { updateWellsList() }, [])

  const onSelect = (value, node) => {
    if (value)
      history.push(value);
    console.log(value)
  }

  return (
    <LoaderPortal show={showLoader}>
      <TreeSelect
        className='header-tree-select'
        bordered={false}
        dropdownMatchSelectWidth={false}
        placeholder='Выберите месторождение'
        treeData={wellsTree}
        treeDefaultExpandAll
        onSelect={onSelect}
        value = {routeMatch?.url}
      />
    </LoaderPortal>
  )
}