import {
  CachePolicy,
  ListOperationResultStatus,
} from '@sudoplatform/sudo-common'
import { Card, VSpace } from '@sudoplatform/web-ui'
import { Select } from 'antd'
import React, { useContext, useState } from 'react'
import { useAsync, useAsyncFn } from 'react-use'
import { AppContext } from '../../containers/AppContext'
import { ErrorFeedback } from '../ErrorFeedback'
import { LearnMore } from '../LearnMore'
import { TransactionList } from './TransactionList'

export const TransactionManagement: React.FC = () => {
  const { virtualCardsClient } = useContext(AppContext)

  const [, setChosenCardId] = useState<string | undefined>(undefined)

  const virtualCardsResult = useAsync(async () => {
    const result = await virtualCardsClient.listVirtualCards({
      cachePolicy: CachePolicy.RemoteOnly,
    })
    if (result.status === ListOperationResultStatus.Failure) {
      throw new Error('Failed to list virtual cards')
    }
    return result.items
  })

  const [listTransactionsResult, listTransactions] = useAsyncFn(
    async (cardId: string) => {
      return await virtualCardsClient.listTransactionsByCardId({ cardId })
    },
  )

  return (
    <Card title="Transaction Management">
      <VSpace spacing="large">
        <LearnMore
          nameText="Transaction Management"
          helpText="Transaction records represent a transaction performed against a provisioned virtual card. Transactions cannot be created or deleted by the consumer directly. Transactions are generated by using the virtual card to make purchases at merchants."
          helpUrl="https://docs.sudoplatform.com/guides/virtual-cards/manage-transactions"
        />
      </VSpace>
      {virtualCardsResult.error ? (
        <ErrorFeedback
          message="An Error occurred trying to list cards"
          error={virtualCardsResult.error}
        />
      ) : virtualCardsResult.value?.length ? (
        <Select
          placeholder="Please choose a Virtual Card..."
          options={virtualCardsResult.value.map((c) => ({
            key: c.id,
            value: c.id,
            label: `${c.alias} **** ${c.last4}`,
          }))}
          onSelect={(value: string) => {
            if (value) {
              const cardId = value
              void listTransactions(cardId)
              setChosenCardId(cardId)
            }
          }}
        />
      ) : (
        <>Please add a virtual card</>
      )}
      <TransactionList listTransactionsResult={listTransactionsResult} />
    </Card>
  )
}
