import { Group, Divider, Flex, MantineSize, Typography } from '@tidbcloud/uikit'
import { observer } from 'mobx-react'
import React from 'react'

import { useGetMonthlyCost, useGetTenantsCreditsSummary } from 'dbaas/services/billing'
import { FormsBillingConfig, FormsMonthlycostExplorerResult } from 'dbaas/services/billing/interface'
import useStores from 'dbaas/stores/useStores'

import { CostsLabel } from './CostsItem'
import { MoneyValue } from './MoneyValue'

export const OnDemandBillingOverview: React.FC<
  React.PropsWithChildren<{
    bill?: FormsMonthlycostExplorerResult
    spacing?: MantineSize | number
  }>
> = ({ bill, spacing = 64 }) => {
  const runningTotal = Number(bill?.total_costs?.raw_price)
  const discount = -Number(bill?.total_costs?.discount_price || '0')
  const totalCost = Number(bill?.invoice_costs?.cost_price)
  const credit = -Number(bill?.credits_costs?.cost_price || '0')
  const totalCostLabel = (
    <>
      Total Cost{' '}
      <Typography span variant="label-sm" c="carbon.6">
        (without taxes)
      </Typography>
    </>
  )

  const items = [
    {
      key: 'running-total',
      label: 'Running Total',
      value: <MoneyValue amount={runningTotal} />
    },
    {
      key: 'discounts',
      label: 'Discounts',
      value: <MoneyValue amount={discount} />
    },
    {
      key: 'credits',
      label: 'Credits',
      value: <MoneyValue amount={credit} />
    },
    {
      key: 'total-cost',
      label: totalCostLabel,
      value: <MoneyValue amount={totalCost} />
    }
  ]

  return (
    <Group grow gap={spacing}>
      {items.map((item) => {
        return <CostsLabel key={item.key} label={item.label} value={item.value} />
      })}
    </Group>
  )
}

export const CreditsOverview: React.FC<React.PropsWithChildren<{ billingConfig: FormsBillingConfig }>> = observer(
  ({ billingConfig }) => {
    const {
      store: { tenantData }
    } = useStores()
    const { data: creditSummary } = useGetTenantsCreditsSummary(tenantData.id, billingConfig.billing_config_id, {
      query: {
        refetchInterval: 15 * 1000
      }
    })

    const items = [
      {
        label: 'Total Credits',
        value: <MoneyValue amount={creditSummary?.total_credits || ''} />
      },
      {
        label: 'Available Credits',
        value: <MoneyValue amount={creditSummary?.available_remaining_credits || ''} />
      },
      {
        label: 'Current Usage',
        value: <MoneyValue amount={creditSummary?.total_costed_credits || ''} />
      }
    ]

    return (
      <Group justify="space-between" grow>
        {items.map((item) => {
          return (
            <Flex key={item.label}>
              <Divider orientation="vertical" mr={24} />
              <CostsLabel key={item.label} label={item.label} value={item.value} />
            </Flex>
          )
        })}
      </Group>
    )
  }
)

export const useCurrentBillingCycle = (orgId: string, billingConfig: FormsBillingConfig) => {
  const currentDate = new Date()
  const year = currentDate.getFullYear().toString()
  const month = (currentDate.getMonth() + 1).toString()
  return useGetMonthlyCost(orgId, billingConfig?.billing_config_id, year, month, {
    query: {
      enabled: !!billingConfig && !!billingConfig.billing_config_id
    }
  })
}
