import { useState, useEffect } from 'react'

import { Hub } from '../../../app/providers/Hubs'
import useApiUrlStore from '../../../app/store/apiStore'
import { GridTile } from '../../../components/mollecules'
import { TradeChart } from '../../../components/organism'
import type { Candle, Position } from '../../../generated/ManagingApi'
import {
  DataClient,
  Ticker,
  Timeframe,
  TradingExchanges,
} from '../../../generated/ManagingApi'

type IAvailableTicker = {
  ticker: Ticker
  candles: Candle[]
  lastCandle?: Candle | null
  isFetching: boolean
}

const TradeChartWidget = () => {
  const { apiUrl } = useApiUrlStore()
  const dataClient = new DataClient({}, apiUrl)
  const [positions] = useState<Position[]>([])
  const [tickers, updateTicker] = useState<IAvailableTicker[]>([
    { candles: [], isFetching: true, lastCandle: null, ticker: Ticker.BTC },
  ])

  useEffect(() => {
    const startDate = new Date()
    startDate.setDate(startDate.getDate() - 10)
    const hub = new Hub('candlehub', apiUrl).hub

    tickers.map((t: IAvailableTicker) => {
      dataClient
        .data_GetCandles(
          TradingExchanges.Evm,
          t.ticker,
          startDate,
          Timeframe.FiveMinutes
        )
        .then((data) => {
          updateTicker(
            tickers.map((ct) =>
              ct.ticker == t.ticker
                ? { candles: data, isFetching: false, ticker: t.ticker }
                : ct
            )
          )
          hub.on(t.ticker.toString(), (candle: Candle) => {
            updateTicker(
              tickers.map((ct) =>
                ct.ticker == t.ticker
                  ? {
                      candles: data,
                      isFetching: false,
                      lastCandle: candle,
                      ticker: ct.ticker,
                    }
                  : ct
              )
            )
          })
        })
    })
  }, [])

  return (
    <GridTile title="Trade Chart">
      {tickers
        .filter((t) => !t.isFetching)
        .map((t, key) => (
          <figure key={key}>
            {
              <TradeChart
                candles={t.candles}
                positions={positions}
                width={700}
                height={512}
                signals={[]}
                stream={t.lastCandle}
              ></TradeChart>
            }
          </figure>
        ))}
    </GridTile>
  )
}

export default TradeChartWidget
