import { StopIcon } from '@heroicons/react/solid'
import moment from 'moment'
import React from 'react'

import useApiUrlStore from '../../../app/store/apiStore'
import {
  TradeDirection,
  type Position,
  Ticker,
  PositionStatus,
  TradingClient,
} from '../../../generated/ManagingApi'
import { Toast, Table } from '../../mollecules'

import PositionStatusBadge from './PositionStatusBadge'

type IPositionList = {
  positions: Position[]
  isFetching: boolean
}

const PositionsList: React.FC<IPositionList> = ({ positions, isFetching }) => {
  const { apiUrl } = useApiUrlStore()

  async function closePosition(identifier: string) {
    const t = new Toast('Closing position')
    const client = new TradingClient({}, apiUrl)
    await client
      .trading_ClosePosition(identifier)
      .then(() => {
        t.update('success', 'Position closed')
      })
      .catch((err) => {
        t.update('error', 'Error :' + err)
      })
  }

  const columns = React.useMemo(
    () => [
      {
        Cell: ({ cell }: any) => (
          <>
            <div
              className="tooltip z-20"
              data-tip={Object.values(PositionStatus)[cell.value]}
            >
              <PositionStatusBadge
                status={Object.values(PositionStatus)[cell.value]}
              />
            </div>
          </>
        ),
        Header: 'Status',
        accessor: 'status',
        disableFilters: true,
        sortType: 'basic',
      },

      {
        Cell: ({ cell }: any) => <div>{Object.values(Ticker)[cell.value]}</div>,
        Header: 'Ticker',
        accessor: 'ticker',
        disableFilters: true,
        disableSortBy: true,
      },
      {
        Cell: ({ cell }: any) => (
          <div>{Object.values(TradeDirection)[cell.value]}</div>
        ),
        Header: 'Direction',
        accessor: 'originDirection',
        disableFilters: true,
        disableSortBy: true,
      },
      {
        Header: 'Account',
        accessor: 'accountName',
        disableFilters: true,
        disableSortBy: true,
      },
      {
        Cell: ({ cell }: any) => moment(cell.value).fromNow(),
        Header: 'Date',
        accessor: 'date',
        disableFilters: true,
      },
      {
        Cell: ({ cell }: any) => (
          <div>{(cell.value.realized as number).toFixed(4)} $</div>
        ),
        Header: 'uPNL',
        accessor: 'profitAndLoss',
        disableFilters: true,
      },
      {
        Cell: ({ cell }) => (
          <>
            <div className="tooltip" data-tip="Close position">
              <button
                data-value={cell.row.value}
                onClick={() => closePosition(cell.value)}
              >
                <StopIcon className="text-error w-4"></StopIcon>
              </button>
            </div>
          </>
        ),
        Header: 'Actions',
        accessor: 'identifier',
        disableFilters: true,
      },
    ],
    []
  )
  return (
    <div className="flex flex-wrap">
      {isFetching ? (
        <div>
          <progress className="progress progress-primary w-56"></progress>
        </div>
      ) : (
        <Table columns={columns} data={positions} />
      )}
    </div>
  )
}

export default PositionsList
