import { useState, useEffect } from 'react'

import { Hub } from '../../../app/providers/Hubs'
import useApiUrlStore from '../../../app/store/apiStore'
import { GridTile } from '../../../components/mollecules'
import { PositionsList } from '../../../components/organism'
import type { Position } from '../../../generated/ManagingApi'

const PositionsWidget = () => {
  const { workerUrl } = useApiUrlStore()
  const [positions, setPositions] = useState<Position[]>([])
  const [isFetching, setIsFetching] = useState(true)

  useEffect(() => {
    const hub = new Hub('positionhub', workerUrl).hub
    hub.on('Positions', (positions) => {
      setPositions(positions)
      setIsFetching(false)
    })
  }, [])

  return (
    <GridTile title="Open Positions">
      <PositionsList
        positions={positions}
        isFetching={isFetching}
      ></PositionsList>
    </GridTile>
  )
}

export default PositionsWidget
