/* eslint-disable react/no-unstable-nested-components */
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { formatBNStr, formatCreditAmount, formatToDate, Table, usePaymentContext } from '@blocklet/payment-react';
import type { TCreditGrantExpanded } from '@blocklet/payment-types';
import { Box, Chip, Divider, styled, Typography } from '@mui/material';
import { useNavigate } from 'react-router-dom';

interface RelatedCreditGrantsProps {
  grants: TCreditGrantExpanded[];
  showDivider?: boolean;
  mode?: 'dashboard' | 'portal';
}

export function StatusChip({ status, label = '' }: { status: string; label?: string }) {
  const getStatusColor = (statusValue: string) => {
    switch (statusValue) {
      case 'granted':
        return 'success';
      case 'pending':
        return 'warning';
      case 'expired':
        return 'default';
      case 'depleted':
        return 'default';
      case 'voided':
        return 'default';
      default:
        return 'default';
    }
  };

  return <Chip label={label || status} size="small" color={getStatusColor(status) as any} />;
}

export default function RelatedCreditGrants({ grants, showDivider = true, mode = 'portal' }: RelatedCreditGrantsProps) {
  const { t, locale } = useLocaleContext();
  const { session } = usePaymentContext();
  const navigate = useNavigate();

  const isAdmin = ['owner', 'admin'].includes(session?.user?.role || '');

  const inDashboard = mode === 'dashboard' && isAdmin;

  if (!grants?.length) {
    return null;
  }

  const handleShowGrantDetail = (grant: TCreditGrantExpanded) => {
    let path = `/customer/credit-grant/${grant.id}`;
    if (inDashboard) {
      path = `/admin/customers/${grant.id}`;
    }
    navigate(path);
  };

  const columns = [
    {
      label: t('common.name'),
      name: 'name',
      options: {
        customBodyRenderLite: (_: string, index: number) => {
          const grant = grants[index] as TCreditGrantExpanded;
          return <Box onClick={() => handleShowGrantDetail(grant)}>{grant.name || grant.id}</Box>;
        },
      },
    },
    {
      label: t('common.status'),
      name: 'status',
      options: {
        customBodyRenderLite: (_: string, index: number) => {
          const grant = grants[index] as TCreditGrantExpanded;
          return (
            <Box onClick={() => handleShowGrantDetail(grant)}>
              <StatusChip status={grant.status} label={t(`admin.customer.creditGrants.status.${grant.status}`)} />
            </Box>
          );
        },
      },
    },
    {
      label: t('common.remainingCredit'),
      name: 'remaining_amount',
      align: 'right',
      options: {
        customBodyRenderLite: (_: string, index: number) => {
          const grant = grants[index] as TCreditGrantExpanded;
          return (
            <Box onClick={() => handleShowGrantDetail(grant)}>
              <Typography variant="body2">
                {formatCreditAmount(
                  formatBNStr(grant.remaining_amount, grant.paymentCurrency?.decimal || 0),
                  grant.paymentCurrency?.symbol || ''
                )}
              </Typography>
            </Box>
          );
        },
      },
    },
    {
      label: t('common.scope'),
      name: 'scope',
      options: {
        customBodyRenderLite: (_: string, index: number) => {
          const grant = grants[index] as TCreditGrantExpanded;
          let scope = 'general';
          if (grant.applicability_config?.scope?.prices) {
            scope = 'specific';
          }
          return (
            <Box onClick={() => handleShowGrantDetail(grant)}>
              {scope === 'specific' ? t('common.specific') : t('common.general')}
            </Box>
          );
        },
      },
    },
    {
      label: t('common.effectiveDate'),
      name: 'effective_at',
      options: {
        customBodyRenderLite: (_: string, index: number) => {
          const grant = grants[index] as TCreditGrantExpanded;
          const effectiveAt = grant.effective_at ? grant.effective_at * 1000 : grant.created_at;
          return (
            <Box onClick={() => handleShowGrantDetail(grant)}>
              {formatToDate(effectiveAt, locale, 'YYYY-MM-DD HH:mm')}
            </Box>
          );
        },
      },
    },
    {
      label: t('common.expirationDate'),
      name: 'expires_at',
      options: {
        customBodyRenderLite: (_: string, index: number) => {
          const grant = grants[index] as TCreditGrantExpanded;
          return (
            <Box onClick={() => handleShowGrantDetail(grant)}>
              <Typography variant="body2">
                {grant.expires_at ? formatToDate(grant.expires_at * 1000, locale, 'YYYY-MM-DD HH:mm') : '-'}
              </Typography>
            </Box>
          );
        },
      },
    },
  ];

  return (
    <>
      {showDivider && <Divider />}
      <TableRoot className="section">
        <Typography
          variant="h3"
          className="section-header"
          sx={{
            mb: 2,
          }}>
          {t('admin.customer.creditGrants.relatedGrants')}
        </Typography>
        <Table
          data={grants}
          columns={columns}
          options={{
            count: grants.length,
            page: 0,
            rowsPerPage: grants.length,
            pagination: false,
          }}
          loading={false}
          toolbar={false}
          footer={false}
          emptyNodeText={t('admin.customer.creditGrants.noGrants')}
        />
      </TableRoot>
    </>
  );
}

const TableRoot = styled(Box)`
  @media (max-width: ${({ theme }) => theme.breakpoints.values.md}px) {
    .MuiTable-root > .MuiTableBody-root > .MuiTableRow-root > td.MuiTableCell-root {
      > div {
        width: fit-content;
        flex: inherit;
        font-size: 14px;
      }
    }
    .invoice-summary {
      padding-right: 20px;
    }
  }
`;
