/* eslint-disable react/no-unstable-nested-components */
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import {
  api,
  formatTime,
  CreditTransactionsList,
  CreditStatusChip,
  getCustomerAvatar,
  TxLink,
  formatCreditAmount,
  formatBNStr,
} from '@blocklet/payment-react';
import type { TCreditGrantExpanded } from '@blocklet/payment-types';
import { ArrowBackOutlined } from '@mui/icons-material';
import { Alert, Avatar, Box, Button, CircularProgress, Divider, Stack, Typography } from '@mui/material';
import { useRequest } from 'ahooks';
import { useNavigate, useParams } from 'react-router-dom';
import { styled } from '@mui/system';
import { useCallback } from 'react';
import InfoMetric from '../../../components/info-metric';
import { useSessionContext } from '../../../contexts/session';
import SectionHeader from '../../../components/section/header';
import CreditGrantItemList from '../../../components/customer/credit-grant-item-list';
import InfoRow from '../../../components/info-row';
import InfoRowGroup from '../../../components/info-row-group';
import { useArcsphere } from '../../../hooks/browser';

const fetchData = (id: string | undefined): Promise<TCreditGrantExpanded> => {
  return api.get(`/api/credit-grants/${id}`).then((res: any) => res.data);
};

export default function CustomerCreditGrantDetail() {
  const { id } = useParams() as { id: string };
  const navigate = useNavigate();
  const { t } = useLocaleContext();
  const { session } = useSessionContext();
  const inArcsphere = useArcsphere();
  const { loading, error, data } = useRequest(() => fetchData(id));

  const handleBack = useCallback(() => {
    navigate('/customer', { replace: true });
  }, [navigate]);

  if (data?.customer?.did && session?.user?.did && data.customer.did !== session.user.did) {
    return <Alert severity="error">{t('common.accessDenied')}</Alert>;
  }
  if (error) {
    return <Alert severity="error">{error.message}</Alert>;
  }

  if (loading || !data) {
    return <CircularProgress />;
  }

  const isDepleted = data?.status === 'depleted';

  const getStatusText = (status: string) => {
    switch (status) {
      case 'granted':
        return t('admin.customer.creditGrants.status.granted');
      case 'pending':
        return t('admin.customer.creditGrants.status.pending');
      case 'depleted':
        return t('admin.customer.creditGrants.status.depleted');
      case 'expired':
        return t('admin.customer.creditGrants.status.expired');
      case 'voided':
        return t('admin.customer.creditGrants.status.voided');
      default:
        return status;
    }
  };

  const getUsagePercentage = () => {
    if (!data.amount || !data.remaining_amount) return 0;
    const total = parseFloat(data.amount);
    const remaining = parseFloat(data.remaining_amount);
    return ((total - remaining) / total) * 100;
  };

  return (
    <Root>
      <Box>
        <Stack
          className="page-header"
          direction="row"
          justifyContent="space-between"
          alignItems="center"
          sx={{ position: 'relative' }}>
          {!inArcsphere ? (
            <Stack
              direction="row"
              onClick={handleBack}
              alignItems="center"
              sx={{ fontWeight: 'normal', cursor: 'pointer' }}>
              <ArrowBackOutlined fontSize="small" sx={{ mr: 0.5, color: 'text.secondary' }} />
              <Typography variant="h6" sx={{ color: 'text.secondary', fontWeight: 'normal' }}>
                {t('admin.customer.creditGrants.title')}
              </Typography>
            </Stack>
          ) : (
            <Box />
          )}
          {data.metadata?.invoice_id && (
            <Button
              variant="outlined"
              size="small"
              onClick={() => navigate(`/customer/invoice/${data.metadata!.invoice_id}`)}>
              {t('admin.customer.creditGrants.viewInvoice')}
            </Button>
          )}
        </Stack>
        <Box
          mt={4}
          sx={{
            display: 'flex',
            gap: {
              xs: 2,
              sm: 2,
              md: 5,
            },
            flexWrap: 'wrap',
            flexDirection: {
              xs: 'column',
              sm: 'column',
              md: 'row',
            },
            alignItems: {
              xs: 'flex-start',
              sm: 'flex-start',
              md: 'center',
            },
          }}>
          <Stack direction="row" justifyContent="space-between" alignItems="center">
            <Stack direction="row" alignItems="center" flexWrap="wrap" gap={1}>
              <Stack direction="column" alignItems="flex-start" justifyContent="space-around">
                <Typography variant="h2" color="text.primary">
                  {data.name || data.id}
                </Typography>
              </Stack>
            </Stack>
          </Stack>
          <Stack
            className="section-body"
            justifyContent="flex-start"
            flexWrap="wrap"
            sx={{
              'hr.MuiDivider-root:last-child': {
                display: 'none',
              },
              flexDirection: {
                xs: 'column',
                sm: 'column',
                md: 'row',
              },
              alignItems: 'flex-start',
              gap: {
                xs: 1,
                sm: 1,
                md: 3,
              },
            }}>
            <InfoMetric
              label={t('common.status')}
              value={<CreditStatusChip status={data.status} label={getStatusText(data.status)} />}
            />
            <InfoMetric
              label={t('admin.customer.creditGrants.originalAmount')}
              value={
                <Stack direction="row" alignItems="center" spacing={0.5}>
                  <Avatar
                    src={data.paymentCurrency?.logo}
                    sx={{ width: 16, height: 16 }}
                    alt={data.paymentCurrency?.symbol}
                  />
                  <Typography variant="body2">
                    {formatCreditAmount(
                      formatBNStr(data.amount, data.paymentCurrency.decimal),
                      data.paymentCurrency.symbol
                    )}
                  </Typography>
                </Stack>
              }
              divider
            />
            <InfoMetric
              label={t('common.remainingCredit')}
              value={
                <Stack direction="row" alignItems="center" spacing={0.5}>
                  <Avatar
                    src={data.paymentCurrency?.logo}
                    sx={{ width: 16, height: 16 }}
                    alt={data.paymentCurrency?.symbol}
                  />
                  <Typography variant="body2">
                    {formatCreditAmount(
                      formatBNStr(data.remaining_amount, data.paymentCurrency.decimal),
                      data.paymentCurrency.symbol
                    )}
                  </Typography>
                </Stack>
              }
              divider
            />
            <InfoMetric
              label={t('admin.customer.creditGrants.usage')}
              value={
                <Typography variant="body2" color={isDepleted ? 'error.main' : 'text.primary'}>
                  {getUsagePercentage().toFixed(1)}%
                </Typography>
              }
              divider
            />
            <InfoMetric
              label={t('common.effectiveDate')}
              value={formatTime(data.effective_at ? data.effective_at * 1000 : data.created_at, 'YYYY-MM-DD HH:mm:ss')}
            />
            {data.expires_at ? (
              <InfoMetric
                label={t('common.expirationDate')}
                value={formatTime(data.expires_at * 1000, 'YYYY-MM-DD HH:mm:ss')}
              />
            ) : null}
          </Stack>
        </Box>
      </Box>
      <Box className="section" sx={{ containerType: 'inline-size' }}>
        <SectionHeader title={t('admin.details')} />
        <InfoRowGroup
          sx={{
            display: 'grid',
            gridTemplateColumns: {
              xs: 'repeat(1, 1fr)',
              xl: 'repeat(2, 1fr)',
            },
            '@container (min-width: 1000px)': {
              gridTemplateColumns: 'repeat(2, 1fr)',
            },
            '.info-row-wrapper': {
              gap: 1,
              flexDirection: {
                xs: 'column',
                xl: 'row',
              },
              alignItems: {
                xs: 'flex-start',
                xl: 'center',
              },
              '@container (min-width: 1000px)': {
                flexDirection: 'row',
                alignItems: 'center',
              },
            },
          }}>
          <InfoRow
            label={t('common.customer')}
            value={
              <Stack direction="row" alignItems="center" spacing={1}>
                <Avatar
                  src={getCustomerAvatar(
                    data.customer?.did,
                    data.customer?.updated_at ? new Date(data.customer.updated_at).toISOString() : '',
                    24
                  )}
                  alt={data.customer?.name}
                  sx={{ width: 24, height: 24 }}
                />
                <Typography>{data.customer?.name}</Typography>
              </Stack>
            }
          />
          <InfoRow
            label={t('common.scope')}
            value={
              <Typography>
                {data.applicability_config?.scope?.prices ? t('common.specific') : t('common.general')}
              </Typography>
            }
          />
          <InfoRow label={t('admin.creditProduct.priority.label')} value={<Typography>{data.priority}</Typography>} />
          <InfoRow label={t('common.createdAt')} value={formatTime(data.created_at)} />
          {data.chain_detail?.mint?.hash && data.paymentMethod?.type === 'arcblock' && (
            <InfoRow
              label={t('common.mintTxHash')}
              value={
                <TxLink
                  details={{ arcblock: { tx_hash: data.chain_detail.mint.hash, payer: '' } }}
                  method={data.paymentMethod}
                  mode="customer"
                />
              }
            />
          )}
        </InfoRowGroup>
      </Box>

      <Divider />
      {data.items && data.items.length > 0 && (
        <>
          <Box className="section">
            <SectionHeader title={t('admin.creditProduct.associatedPrices.label')} />
            <Box className="section-body">
              <CreditGrantItemList data={data.items} currency={data.paymentCurrency} />
            </Box>
          </Box>
          <Divider />
        </>
      )}

      <Divider />
      <Box className="section">
        <Typography variant="h3" className="section-header">
          {t('admin.creditTransactions.title')}
        </Typography>
        <Box className="section-body">
          <CreditTransactionsList
            customer_id={data.customer_id}
            credit_grant_id={data.id}
            showAdminColumns={false}
            showTimeFilter
          />
        </Box>
      </Box>
    </Root>
  );
}

const Root = styled(Stack)`
  margin-bottom: 24px;
  gap: 24px;
  flex-direction: column;
  @media (max-width: ${({ theme }) => theme.breakpoints.values.md}px) {
    . {
      border: none;
      box-shadow: none;
      padding: 0;
    }
    .section-header {
      font-size: 18px;
    }
  }
`;
