import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { api, formatBNStr, formatTime, useMobile } from '@blocklet/payment-react';
import type { TSubscriptionExpanded, CreditGrantSummary } from '@blocklet/payment-types';
import { useRequest } from 'ahooks';

import { Button, Stack, Typography, Tooltip, Avatar, Box, CircularProgress, Skeleton } from '@mui/material';
import { BN } from '@ocap/util';
import { useNavigate } from 'react-router-dom';
import { AccountBalanceWalletOutlined, ArrowForward, InfoOutlined } from '@mui/icons-material';
import InfoMetric from '../info-metric';
import SubscriptionStatus from './status';

type Props = {
  subscription: TSubscriptionExpanded;
  showBalance?: boolean;
  mode?: 'portal' | 'admin';
};

const fetchUpcoming = (id: string): Promise<{ amount: string }> => {
  return api.get(`/api/subscriptions/${id}/upcoming`).then((res: any) => res.data);
};

const fetchPayer = (id: string): Promise<{ token: string; paymentAddress: string }> => {
  return api.get(`/api/subscriptions/${id}/payer-token`).then((res: any) => res.data);
};

const fetchCreditBalance = ({
  customerId,
  subscriptionId,
}: {
  customerId: string;
  subscriptionId: string;
}): Promise<{ [key: string]: CreditGrantSummary }> => {
  return api
    .get(`/api/credit-grants/summary?customer_id=${customerId}&subscription_id=${subscriptionId}`)
    .then((res: any) => res.data);
};

export default function SubscriptionMetrics({ subscription, showBalance = true, mode = 'portal' }: Props) {
  const { t } = useLocaleContext();
  const isCredit = subscription.paymentCurrency?.type === 'credit';
  const { data: upcoming, loading: upcomingLoading } = useRequest(() => fetchUpcoming(subscription.id));
  const navigate = useNavigate();

  const { isMobile } = useMobile();

  const { data: payerValue, loading: payerLoading } = useRequest(() => fetchPayer(subscription.id), {
    ready: showBalance,
  });

  const { data: creditBalance } = useRequest(
    () =>
      fetchCreditBalance({
        customerId: subscription.customer_id,
        subscriptionId: subscription.id,
      }),
    {
      ready: isCredit,
    }
  );

  const supportShowBalance = showBalance && ['arcblock', 'ethereum', 'base'].includes(subscription.paymentMethod.type);

  // let scheduleToCancelTime = 0;
  // if (['active', 'trialing', 'past_due'].includes(subscription.status) && subscription.cancel_at) {
  //   scheduleToCancelTime = subscription.cancel_at * 1000;
  // } else if (subscription.status !== 'canceled' && subscription.cancel_at_period_end) {
  //   scheduleToCancelTime = subscription.current_period_end * 1000;
  // }

  const isInsufficientBalance = new BN(payerValue?.token || '0').lt(new BN(upcoming?.amount || '0'));

  const handleRecharge = () => {
    if (isCredit || mode !== 'portal') {
      return;
    }
    navigate(`/customer/subscription/${subscription.id}/recharge`);
  };
  const renderBalanceValue = () => {
    const balance = isCredit ? creditBalance?.[subscription.paymentCurrency.id]?.remainingAmount : payerValue?.token;
    if (upcomingLoading || payerLoading) {
      return <CircularProgress size={16} />;
    }

    const canRecharge = mode === 'portal';

    if (isInsufficientBalance && !isCredit && canRecharge) {
      return (
        <Button
          component="a"
          color="error"
          sx={{
            height: 24,
            pt: 0,
            pb: 0,
            ...(isMobile ? { textAlign: 'right', maxWidth: 160 } : {}),
          }}
          onClick={() => navigate(`/customer/subscription/${subscription.id}/recharge`)}>
          {t('admin.subscription.insufficientBalance')}
          <ArrowForward sx={{ fontSize: 14 }} />
        </Button>
      );
    }

    return (
      <Stack
        sx={{
          flexDirection: 'row',
          alignItems: 'center',
          gap: 0.5,
          fontSize: '16px',
          fontWeight: 500,
          cursor: 'pointer',
          '&:hover': { color: 'primary.main' },
        }}
        onClick={handleRecharge}>
        <Avatar
          src={subscription.paymentCurrency?.logo}
          sx={{ width: 16, height: 16 }}
          alt={subscription.paymentCurrency?.name}
        />
        <Box
          sx={{
            display: 'flex',
            alignItems: 'baseline',
          }}>
          {formatBNStr(balance, subscription.paymentCurrency.decimal)}
          <Typography sx={{ fontSize: 14, ml: 0.5 }}>{subscription.paymentCurrency.symbol}</Typography>
        </Box>
      </Stack>
    );
  };
  return (
    <>
      <InfoMetric label={t('common.status')} value={<SubscriptionStatus subscription={subscription} />} divider />
      {subscription.status === 'active' && !subscription.cancel_at && (
        <InfoMetric
          label={t('admin.subscription.nextInvoice')}
          value={formatTime(subscription.current_period_end * 1000)}
          divider
        />
      )}
      {['active', 'trialing'].includes(subscription.status) && upcoming?.amount && upcoming.amount !== '0' && (
        <InfoMetric
          label={
            <Typography
              sx={{
                display: 'flex',
                alignItems: 'center',
                gap: 0.5,
                fontSize: 14,
                fontWeight: 500,
              }}>
              {t('admin.subscription.nextInvoiceAmount')}
              <Tooltip title={t('admin.subscription.nextInvoiceAmountTip')} placement="top" arrow>
                <InfoOutlined fontSize="small" sx={{ color: 'text.secondary', cursor: 'pointer', fontSize: '16px' }} />
              </Tooltip>
            </Typography>
          }
          value={`${formatBNStr(upcoming.amount, subscription.paymentCurrency.decimal)} ${
            subscription.paymentCurrency.symbol
          } (${t('common.estimated')})`}
          divider
        />
      )}
      {supportShowBalance && ['active', 'trialing'].includes(subscription.status) && (
        <InfoMetric
          label={
            <Stack
              direction="row"
              spacing={1}
              sx={{
                alignItems: 'center',
                fontWeight: 500,
              }}>
              <Typography
                sx={{
                  fontWeight: 500,
                  fontSize: 14,
                }}>
                {t('admin.subscription.currentBalance')}
              </Typography>
              <Tooltip
                title={
                  <Typography sx={{ fontFamily: 'monospace', fontSize: '13px' }}>
                    {t('admin.subscription.paymentAddress')}：
                    {payerLoading ? <Skeleton width={120} /> : payerValue?.paymentAddress}
                  </Typography>
                }
                placement="top"
                arrow>
                <AccountBalanceWalletOutlined
                  sx={{
                    fontSize: '16px',
                    color: 'text.secondary',
                    cursor: 'pointer',
                    '&:hover': { color: 'primary.main' },
                    display: {
                      xs: 'none',
                      md: 'block',
                    },
                  }}
                />
              </Tooltip>
            </Stack>
          }
          value={renderBalanceValue()}
          divider
        />
      )}
      {/* {scheduleToCancelTime > 0 && (
        <InfoMetric label={t('admin.subscription.cancel.schedule')} value={formatTime(scheduleToCancelTime)} divider />
      )} */}
      {subscription.status === 'canceled' && subscription.canceled_at && (
        <InfoMetric
          label={t('admin.subscription.cancel.done')}
          value={formatTime(subscription.canceled_at * 1000)}
          divider
        />
      )}
    </>
  );
}
