import { Box, Card, Text, openConfirmModal } from '@tidbcloud/uikit'
import { MRT_ColumnDef, ProTable } from '@tidbcloud/uikit/biz'
import { capitalize } from 'lodash-es'
import { observer } from 'mobx-react'
import React from 'react'

import { HeroComponent } from 'dbaas/components/Measurement'
import TimeComponent from 'dbaas/components/TimeComponent'
import { CloudProvidersDescription } from 'dbaas/features/Billing/provider'
import { useListTenantsCredits } from 'dbaas/services/billing'
import { FormsCreditsPackage, FormsBillingConfig } from 'dbaas/services/billing/interface'
import { defaultErrorMsg, getErrorMessage, UnexpectedError } from 'dbaas/services/errorCodes'
import useStores from 'dbaas/stores/useStores'

import { CreditsOverview } from '../components/BillingOverview'
import { MoneyValue } from '../components/MoneyValue'

const statusMap = {
  before_active: 'valid',
  active: 'valid',
  inactive: 'inactive'
}

export const Credits: React.FC<React.PropsWithChildren<{ billingConfig: FormsBillingConfig }>> = observer(
  ({ billingConfig }) => {
    const {
      store: { tenantData }
    } = useStores()

    const { data, isLoading, error, isFetched } = useListTenantsCredits(
      tenantData.id,
      billingConfig.billing_config_id,
      {
        query: {
          refetchOnWindowFocus: false,
          refetchInterval: 60 * 1000
        }
      }
    )
    const errorMsg = error ? getErrorMessage(error) : ''

    const columns: MRT_ColumnDef<FormsCreditsPackage>[] = [
      {
        header: 'Code',
        accessorFn: ({ credits_code }: FormsCreditsPackage) => {
          return (credits_code || '').slice(0, 8).toUpperCase()
        },
        maxSize: 140
      },
      {
        header: 'Status',
        accessorFn: ({ status, closed_reason }: FormsCreditsPackage) => {
          return (closed_reason || statusMap[status || ''] || '').split('_').map(capitalize).join(' ')
        },
        maxSize: 140
      },
      {
        header: 'Services',
        accessorFn: ({ type, bind_types }: FormsCreditsPackage) => {
          if (!type) {
            return '-'
          }
          if (bind_types && bind_types.length <= 2) {
            return type
          }
          return (
            <span>
              {bind_types
                ?.slice(0, 2)
                .map((t) => {
                  return t.name
                })
                .join(', ')}
              ...
              <a
                className="hover:wd-no-underline wd-ml-4px"
                onClick={() => {
                  openConfirmModal({
                    title: 'Credit Type',
                    centered: true,
                    trapFocus: false,
                    size: 'lg',
                    children: <Text>{type}</Text>,
                    labels: {
                      confirm: 'Close',
                      cancel: 'Cancel'
                    },
                    cancelProps: {
                      display: 'none'
                    }
                  })
                }}
              >
                Details
              </a>
            </span>
          )
        }
      },
      {
        header: 'Cloud Provider',
        accessorFn(originalRow) {
          return CloudProvidersDescription[originalRow.provider || ''] || '-'
        }
      },
      {
        header: 'Credit',
        accessorFn: ({ total_credits }: FormsCreditsPackage) => {
          return <MoneyValue amount={total_credits || '0'}></MoneyValue>
        }
      },
      {
        header: 'Remaining Credit',
        accessorFn: ({ remaining_credits }: FormsCreditsPackage) => {
          return <MoneyValue amount={remaining_credits || '0'}></MoneyValue>
        }
      },
      {
        header: 'Start Date',
        accessorFn: ({ start_date }: FormsCreditsPackage) => {
          return <TimeComponent time={start_date || ''} utcOffset={0} format="YYYY-MM-DD HH:mm:ss Z"></TimeComponent>
        },
        minSize: 240
      },
      {
        header: 'Expiry Date',
        accessorFn: ({ expired_date }: FormsCreditsPackage) => {
          return <TimeComponent time={expired_date || ''} utcOffset={0} format="YYYY-MM-DD HH:mm:ss Z"></TimeComponent>
        },
        minSize: 240
      }
    ]

    return (
      <Box pb={96}>
        <Card p={24}>
          <CreditsOverview billingConfig={billingConfig} />
        </Card>
        <Card mt={24} p={24}>
          <ProTable
            columns={columns}
            // mantineTableContainerProps={{ sx: { overflow: 'auto' } }}
            data={data || []}
            emptyMessage="No Credits"
            errorMessage={errorMsg === defaultErrorMsg ? UnexpectedError : errorMsg}
            loading={isLoading}
            // state={{ isLoading }}
          />
        </Card>
        {isFetched && <HeroComponent />}
      </Box>
    )
  }
)
