import { Box, Card, Text, Button, 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 { useListTenantDiscounts } from 'dbaas/services/billing'
import { FormsDiscount, FormsBillingConfig } from 'dbaas/services/billing/interface'
import { defaultErrorMsg, getErrorMessage, UnexpectedError } from 'dbaas/services/errorCodes'
import useStores from 'dbaas/stores/useStores'

import { toUSDiscount } from '../helpers'

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

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

    const columns: MRT_ColumnDef<FormsDiscount>[] = [
      {
        header: 'Code',
        accessorFn: ({ discount_code }) => {
          return (discount_code || '').slice(0, 8).toUpperCase()
        },
        maxSize: 90
      },
      {
        header: 'Status',
        accessorFn: ({ status }) => {
          return capitalize(status)
        },
        maxSize: 80
      },
      {
        header: 'Services',
        accessorFn: ({ unit_filters }) => {
          if (!unit_filters) {
            return '-'
          }
          const type = unit_filters.map((it) => it.name).join(', ')
          if (unit_filters.length <= 1) {
            return type
          }
          return (
            <span>
              {unit_filters
                .slice(0, 1)
                .map((t) => {
                  return t.name
                })
                .join(', ')}
              ...
              <Button
                fz={'1rem'}
                fw={400}
                p={0}
                h="auto"
                pl={4}
                sx={() => ({ ':hover': { textDecoration: 'none' } })}
                component="a"
                variant="subtle"
                onClick={() => {
                  openConfirmModal({
                    title: 'Discount Type',
                    centered: true,
                    trapFocus: false,
                    size: 'lg',
                    children: <Text>{type}</Text>,
                    labels: {
                      confirm: 'Close',
                      cancel: 'Cancel'
                    },
                    cancelProps: {
                      display: 'none'
                    }
                  })
                }}
                data-mp-event="mp-details-1691461016053"
              >
                Details
              </Button>
            </span>
          )
        }
      },
      {
        header: 'Cloud Provider',
        accessorFn(originalRow) {
          return CloudProvidersDescription[originalRow.provider || ''] || '-'
        }
      },
      {
        header: 'Description',
        accessorKey: 'description',
        minSize: 220
      },
      {
        header: 'Discount Percentage (% Off)',
        minSize: 220,
        accessorFn: ({ discount }) => {
          const value = Number.parseFloat(discount || '0') * 100
          return `${toUSDiscount(value)}% Off`
        }
      },
      {
        header: 'Start Date',
        accessorFn: ({ started_at }) => {
          return <TimeComponent time={started_at || ''} utcOffset={0} format="YYYY-MM-DD HH:mm:ss Z"></TimeComponent>
        },
        minSize: 240
      },
      {
        header: 'Expiry Date',
        accessorFn: ({ expired_at }) => {
          return <TimeComponent time={expired_at || ''} utcOffset={0} format="YYYY-MM-DD HH:mm:ss Z"></TimeComponent>
        },
        minSize: 240
      }
    ]

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