import {ArrowDownIcon, ArrowUpIcon, ChevronDownIcon, ChevronRightIcon, PlayIcon,} from '@heroicons/react/solid'
import React, {useEffect, useState} from 'react'

import {Hub} from '../../../app/providers/Hubs'
import useApiUrlStore from '../../../app/store/apiStore'
import type {Account, TradingBot} from '../../../generated/ManagingApi'
import {AccountClient, BotClient, TradeDirection, TradeStatus,} from '../../../generated/ManagingApi'
import {SelectColumnFilter, Table} from '../../mollecules'
import StatusBadge from '../StatusBadge/StatusBadge'
import Summary from '../Trading/Summary'
import BotRowDetails from './botRowDetails'

export default function ActiveBots() {
  const [bots, setBots] = useState<TradingBot[]>([])
  const [accounts, setAccounts] = useState<Account[]>([])
  const { apiUrl } = useApiUrlStore()

  const columns = React.useMemo(
    () => [
      {
        Cell: ({ row }: any) => (
          // Use Cell to render an expander for each row.
          // We can use the getToggleRowExpandedProps prop-getter
          // to build the expander.
          <span {...row.getToggleRowExpandedProps()}>
            {row.isExpanded ? (
              <ChevronDownIcon></ChevronDownIcon>
            ) : (
              <ChevronRightIcon></ChevronRightIcon>
            )}
          </span>
        ),

        // Make sure it has an ID
        Header: ({ getToggleAllRowsExpandedProps, isAllRowsExpanded }: any) => (
          <span {...getToggleAllRowsExpandedProps()}>
            {isAllRowsExpanded ? 'v' : '>'}
          </span>
        ),
        // Build our expander column
        id: 'expander',
      },
      {
        Cell: ({ cell }: any) => (
          <>
            <StatusBadge
              status={cell.row.values.status}
              isForWatchOnly={cell.row.values.isForWatchingOnly}
            />
          </>
        ),
        Header: 'Status',
        accessor: 'status',
        disableFilters: true,
        disableSortBy: true,
        search: false,
      },
      {
        accessor: 'isForWatchingOnly',
        disableFilters: true,
        disableSortBy: true,
        search: false,
      },
      {
        Filter: SelectColumnFilter,
        Header: 'Ticker',
        accessor: 'ticker',
        disableSortBy: true,
      },
      {
        Header: 'Account',
        accessor: 'accountName',
      },
      {
        Filter: SelectColumnFilter,
        Header: 'Timeframe',
        accessor: 'timeframe',
        disableSortBy: true,
      },
      {
        Filter: SelectColumnFilter,
        Header: 'Scenario',
        accessor: 'scenario',
        disableSortBy: true,
      },
      {
        Cell: ({ cell }: any) => (
          <>
            {
              <>
                {
                  cell.row.values.positions.filter(
                    (p: any) => p.originDirection == TradeDirection.Long
                  ).length
                }{' '}
                <ArrowUpIcon
                  width="10"
                  className="text-primary inline"
                  display="initial"
                ></ArrowUpIcon>
                {' | '}
                {
                  cell.row.values.positions.filter(
                    (p: any) => p.originDirection == TradeDirection.Short
                  ).length
                }{' '}
                <ArrowDownIcon
                  width="10"
                  className="text-accent inline"
                  display="initial"
                ></ArrowDownIcon>{' '}
                {
                  cell.row.values.positions.filter(
                    (p: any) => p.status == TradeStatus.Filled
                  ).length
                }{' '}
                <PlayIcon
                  width="10"
                  className="text-accent inline"
                  display="initial"
                ></PlayIcon>{' '}
              </>
            }
          </>
        ),
        Header: 'Positions',
        accessor: 'positions',
        disableFilters: true,
      },
      {
        Cell: ({ cell }) => <>{cell.row.values.winRate} %</>,
        Header: 'Winrate',
        accessor: 'winRate',
        disableFilters: true,
      },
      {
        Cell: ({ cell }) => <>{cell.row.values.profitAndLoss} $</>,
        Header: 'PNL',
        accessor: 'profitAndLoss',
        disableFilters: true,
      },
    ],
    []
  )

  useEffect(() => {
    setupHubConnection().then(() => {
      if (bots.length == 0) {
        const client = new BotClient({}, apiUrl)
        client.bot_GetActiveBots().then((data) => {
          setBots(data)
        })
      }
    })
    const client = new AccountClient({}, apiUrl)
    client.account_GetAccounts().then((data) => {
      setAccounts(data)
    })
  }, [])

  const setupHubConnection = async () => {
    const hub = new Hub('bothub', apiUrl).hub

    hub.on('BotsSubscription', (data: TradingBot[]) => {
      // eslint-disable-next-line no-console
      console.log(
        'bot List',
        bots.map((bot) => {
          return bot.name
        })
      )
      setBots(data)
    })

    return hub
  }

  const renderRowSubComponent = React.useCallback(
    ({ row }: any) => (
      <>
        <BotRowDetails
          bot={row.original}
        ></BotRowDetails>
      </>
    ),
    []
  )

  return (
    <>
      <div className="flex flex-wrap">
        <Summary bots={bots} accounts={accounts}></Summary>
      </div>
      <div className="flex flex-wrap">
        <Table
          columns={columns}
          data={bots}
          renderRowSubCompontent={renderRowSubComponent}
          hiddenColumns={['isForWatchingOnly']}
        />
      </div>
    </>
  )
}
