import { useComputedColorScheme, useMantineTheme } from '@tidbcloud/uikit'
import { MRT_Cell, MRT_ColumnDef, MRT_Row, ProTable } from '@tidbcloud/uikit/biz'
import { IconBezierCurve02, IconFolder, IconHome04 } from '@tidbcloud/uikit/icons'
import React, { useMemo } from 'react'

import { FormsMonthlycostExplorerResult } from 'dbaas/services/billing/interface'

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

import { CostsItem, createFooterRenders, renderCellWithTips, renderCustomExpandCell, toNegative } from './helpers'

interface ProjectBillsTableProps {
  data: CostsItem[]
  loading: boolean
  error: string
  currentBill?: FormsMonthlycostExplorerResult
  withServicePlan?: boolean
  withSorting?: boolean
}

export const ProjectBillsTable: React.FC<ProjectBillsTableProps> = ({
  data,
  loading,
  error,
  currentBill,
  withServicePlan = false,
  withSorting = false
}) => {
  const colorScheme = useComputedColorScheme()
  const isLight = colorScheme === 'light'
  const theme = useMantineTheme()

  const footerRenders = useMemo(() => createFooterRenders(currentBill, isLight, theme), [currentBill, isLight, theme])

  const cellWrapper = (row: MRT_Row<CostsItem>, cell: MRT_Cell<CostsItem>) => {
    const name = row.original.name
    const value = cell.getValue() as any as React.ReactNode
    const depth = row.depth
    const canExpand = row.getCanExpand()
    if ((row.original.servicePlan || '').toLowerCase() === 'lake' && depth === 0) {
      return (
        <>
          <IconHome04 size={16} c="carbon.7" mr={8} ml={canExpand ? 0 : -6} /> {value}
        </>
      )
    }
    if (
      ['premium', 'essential', 'starter', 'byoc'].includes((row.original.servicePlan || '').toLowerCase()) &&
      depth === 0
    ) {
      return (
        <>
          <IconBezierCurve02 size={16} c="carbon.7" mr={8} ml={canExpand ? 0 : -6} /> {value}
        </>
      )
    }
    if (name.toLowerCase() !== 'other charges' && depth === 0) {
      return (
        <>
          <IconFolder size={16} c="carbon.7" mr={8} ml={canExpand ? 0 : -6} /> {value}
        </>
      )
    }
    return value
  }

  const columns: MRT_ColumnDef<CostsItem>[] = [
    {
      id: 'name',
      header: withServicePlan ? 'Project & Resource Bills' : 'Project Bills',
      accessorKey: 'name',
      enableSorting: false,
      Cell: withServicePlan
        ? ({ row, cell, ...rest }) => renderCustomExpandCell({ row, cell, cellWrapper, ...rest })
        : renderCellWithTips,
      footer: loading ? undefined : 'Total',
      mantineTableHeadCellProps: {
        sx: {
          paddingLeft: '12px !important'
        }
      },
      mantineTableBodyCellProps: {
        sx: {
          paddingLeft: '12px !important'
        }
      },
      mantineTableFooterCellProps: {
        sx: {
          paddingLeft: '12px !important'
        }
      }
    },
    {
      header: 'Running Total',
      accessorFn: (row) => <MoneyValue monospaced amount={row.costs?.raw_price || '0'} />,
      Footer: loading ? undefined : footerRenders.runningTotal,
      enableSorting: withSorting,
      mantineTableHeadCellProps: {
        align: 'right',
        sx: withSorting
          ? {
              '.mrt-table-head-cell-labels': {
                flexDirection: 'row'
              }
            }
          : undefined
      },
      mantineTableBodyCellProps: {
        align: 'right'
      },
      sortingFn: (rowA, rowB) => {
        return (Number(rowA.original.costs?.raw_price) || 0) - (Number(rowB.original.costs?.raw_price) || 0)
      }
    },
    {
      header: 'Discounts',
      accessorFn: (row) => {
        return <MoneyValue monospaced amount={toNegative(row.costs?.discount_price || '0')} negativeZero />
      },
      Footer: loading ? undefined : footerRenders.discounts,
      mantineTableHeadCellProps: {
        align: 'right'
      },
      mantineTableBodyCellProps: {
        align: 'right'
      },
      enableSorting: false
    },
    {
      header: 'Credits',
      accessorFn: (row) => <MoneyValue monospaced amount={toNegative(row.credit?.cost_price || '0')} negativeZero />,
      Footer: loading ? undefined : footerRenders.credits,
      mantineTableHeadCellProps: {
        align: 'right'
      },
      mantineTableBodyCellProps: {
        align: 'right'
      },
      enableSorting: false
    },
    {
      header: 'Total Cost',
      accessorFn: (row) => <MoneyValue monospaced amount={row.bill?.cost_price || '0'} />,
      id: 'usage',
      Footer: loading ? undefined : footerRenders.totalCost,
      size: 106,
      mantineTableHeadCellProps: {
        align: 'right',
        sx: {
          paddingRight: '12px !important',
          ...(withSorting
            ? {
                '.mrt-table-head-cell-labels': {
                  flexDirection: 'row'
                }
              }
            : undefined)
        }
      },
      mantineTableBodyCellProps: {
        align: 'right',
        sx: {
          paddingRight: '12px !important'
        }
      },
      mantineTableFooterCellProps: {
        align: 'right',
        sx: {
          paddingRight: '12px !important'
        }
      },
      enableSorting: true,
      sortingFn: (rowA, rowB) => {
        return (Number(rowA.original.bill?.cost_price) || 0) - (Number(rowB.original.bill?.cost_price) || 0)
      }
    }
  ]

  return (
    <ProTable
      columns={columns}
      data={data}
      loading={loading}
      enableExpanding
      emptyMessage={'No Data'}
      errorMessage={error}
      enableSorting={withSorting}
      mantinePaperProps={{ mt: 8 }}
      mantineTableFooterProps={{ display: data.length ? undefined : 'none' }}
    />
  )
}
