/* eslint-disable react/no-unstable-nested-components */
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import Toast from '@arcblock/ux/lib/Toast';
import {
  api,
  SlippageConfig,
  CreditTransactionsList,
  CustomerInvoiceList,
  formatBNStr,
  formatError,
  formatExchangeRateDisplay,
  formatTime,
  getPrefix,
  hasDelegateTxHash,
  TxLink,
  useMobile,
  usePaymentContext,
} from '@blocklet/payment-react';
import type { SlippageConfigValue } from '@blocklet/payment-react';
import type { TPaymentCurrency, TSubscriptionExpanded } from '@blocklet/payment-types';
import {
  AccountBalanceWalletOutlined,
  ArrowBackOutlined,
  CheckCircle,
  HelpOutline,
  SettingsOutlined,
} from '@mui/icons-material';
import {
  Alert,
  Avatar,
  Box,
  Button,
  CircularProgress,
  Divider,
  IconButton,
  Link as MuiLink,
  Dialog,
  DialogContent,
  DialogTitle,
  Stack,
  Tooltip,
  Typography,
  useTheme,
} from '@mui/material';
import { styled } from '@mui/system';
import { BN, fromUnitToToken } from '@ocap/util';
import { useRequest } from 'ahooks';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Link, useNavigate, useParams } from 'react-router-dom';
import { joinURL } from 'ufo';
import Currency from '../../../components/currency';
import CustomerLink from '../../../components/customer/link';
import InfoMetric from '../../../components/info-metric';
import InfoRow from '../../../components/info-row';
import InfoRowGroup from '../../../components/info-row-group';
import SubscriptionDescription from '../../../components/subscription/description';
import SubscriptionItemList from '../../../components/subscription/items';
import SubscriptionMetrics from '../../../components/subscription/metrics';
import SubscriptionActions, { ActionMethods } from '../../../components/subscription/portal/actions';
import VendorServiceList from '../../../components/subscription/vendor-service-list';
import DiscountInfo from '../../../components/discount/discount-info';
import { useSessionContext } from '../../../contexts/session';
import {
  usePendingAmountForSubscription,
  useSubscriptionExchangeRate,
  useUnpaidInvoicesCheckForSubscription,
} from '../../../hooks/subscription';
import { formatSmartDuration, TimeUnit } from '../../../libs/dayjs';
import { canChangePaymentMethod } from '../../../libs/util';
import PaymentMethodInfo from '../../../components/subscription/payment-method-info';
import { useArcsphere } from '../../../hooks/browser';

const defaultSlippageConfig: SlippageConfigValue = { mode: 'percent', percent: 0.5 };

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

const fetchOverdraftProtection = (
  id: string
): Promise<{ enabled: boolean; remaining: string; unused: string; upcoming: { amount: string }; gas: string }> => {
  return api.get(`/api/subscriptions/${id}/overdraft-protection`).then((res: any) => res.data);
};

const fetchCycleAmount = (
  subscriptionId: string,
  params: { overdraftProtection: boolean }
): Promise<{ amount: string; gas: string; currency: TPaymentCurrency }> => {
  return api.get(`/api/subscriptions/${subscriptionId}/cycle-amount`, { params }).then((res: any) => res.data);
};

export default function CustomerSubscriptionDetail() {
  const { id } = useParams() as { id: string };
  const navigate = useNavigate();
  const { t, locale } = useLocaleContext();
  const { isMobile } = useMobile();
  const { session } = useSessionContext();
  const { connect } = usePaymentContext();
  const inArcsphere = useArcsphere();
  const { loading, error, data, refresh } = useRequest(() => fetchData(id));
  const { hasUnpaid, checkUnpaidInvoices } = useUnpaidInvoicesCheckForSubscription(id);
  const { hasPendingAmount, pendingAmount } = usePendingAmountForSubscription(id, data?.paymentCurrency);
  const overdraftProtectionReady =
    ['active', 'trialing', 'past_due'].includes(data?.status || '') && data?.paymentMethod?.type === 'arcblock';
  const [slippageDialogOpen, setSlippageDialogOpen] = useState(false);
  const [slippageConfig, setSlippageConfig] = useState<SlippageConfigValue>(defaultSlippageConfig);
  const [savedSlippageConfig, setSavedSlippageConfig] = useState<SlippageConfigValue>(defaultSlippageConfig);
  const [slippageSaving, setSlippageSaving] = useState(false);
  const { liveRateInfo } = useSubscriptionExchangeRate({
    subscriptionId: id,
    currencyId: data?.paymentCurrency?.id,
    enabled: !!data?.paymentCurrency?.id,
  });
  useEffect(() => {
    const rawConfig = (data as any)?.slippage_config;
    if (rawConfig && typeof rawConfig === 'object') {
      const mode: 'percent' | 'rate' = rawConfig.mode === 'rate' ? 'rate' : 'percent';
      const percentValue = Number(rawConfig.percent);
      const percent = Number.isFinite(percentValue) && percentValue >= 0 ? percentValue : 0.5;
      const normalized: SlippageConfigValue = {
        mode,
        percent,
        ...(rawConfig.min_acceptable_rate ? { min_acceptable_rate: String(rawConfig.min_acceptable_rate) } : {}),
        ...(rawConfig.base_currency ? { base_currency: String(rawConfig.base_currency) } : {}),
        ...(rawConfig.updated_at_ms ? { updated_at_ms: Number(rawConfig.updated_at_ms) } : {}),
      };
      setSlippageConfig(normalized);
      setSavedSlippageConfig(normalized);
      return;
    }
    setSlippageConfig(defaultSlippageConfig);
    setSavedSlippageConfig(defaultSlippageConfig);
  }, [data]);

  // Check if subscription has any dynamic pricing items
  // Slippage settings are only relevant for dynamic pricing subscriptions
  const hasDynamicPricing = useMemo(
    () =>
      (data?.items || []).some((item: any) => {
        const price = item.upsell_price || item.price;
        return price && (price as any)?.pricing_type === 'dynamic';
      }),
    [data?.items]
  );

  // Calculate display min_acceptable_rate
  // If min_acceptable_rate is not set (e.g., trial period with percent mode), calculate from live rate
  const displayMinAcceptableRate = useMemo(() => {
    // If already has min_acceptable_rate, use it directly
    if (slippageConfig.min_acceptable_rate) {
      return slippageConfig.min_acceptable_rate;
    }
    // For percent mode without min_acceptable_rate, calculate from live rate
    if (liveRateInfo?.rate && slippageConfig.percent !== undefined) {
      const rate = Number(liveRateInfo.rate);
      const { percent } = slippageConfig;
      if (Number.isFinite(rate) && rate > 0 && Number.isFinite(percent)) {
        // min_rate = rate * (1 - percent/100)
        const minRate = rate * (1 - percent / 100);
        // Format to reasonable precision (8 decimals for crypto rates)
        return minRate.toFixed(8).replace(/\.?0+$/, '');
      }
    }
    return null;
  }, [slippageConfig.min_acceptable_rate, slippageConfig.percent, liveRateInfo?.rate]);

  const {
    data: overdraftProtection = null,
    loading: overdraftProtectionLoading,
    run: refreshOverdraftProtection,
  } = useRequest(() => fetchOverdraftProtection(id), {
    ready: overdraftProtectionReady,
  });

  const muiTheme = useTheme();

  const {
    data: cycleAmount = {
      amount: '0',
      gas: '0',
    },
  } = useRequest(
    () =>
      fetchCycleAmount(id, {
        overdraftProtection: true,
      }),
    {
      refreshDeps: [id],
      ready: overdraftProtectionReady,
    }
  );

  const actionRef = useRef<ActionMethods | undefined>(undefined);

  const enableOverdraftProtection = !!overdraftProtection?.enabled;

  const actionSetUp = useCallback((methods: ActionMethods) => {
    actionRef.current = methods;
  }, []);

  const handleSlippageDialogClose = useCallback(() => {
    setSlippageDialogOpen(false);
    setSlippageConfig(savedSlippageConfig);
  }, [savedSlippageConfig]);

  const handleSlippageSave = async () => {
    if (!id) {
      return;
    }
    setSlippageSaving(true);
    try {
      const payloadConfig = {
        ...slippageConfig,
        ...(slippageConfig.base_currency ? {} : { base_currency: liveRateInfo?.base_currency || 'USD' }),
      };
      const result = await api.put(`/api/subscriptions/${id}/slippage`, {
        slippage_config: payloadConfig,
      });
      setSavedSlippageConfig(payloadConfig);
      await refresh();
      setSlippageDialogOpen(false);

      // Check if delegation is insufficient and needs re-authorization
      const delegationWarning = result.data?.delegation_warning;
      if (delegationWarning && !delegationWarning.sufficient) {
        // Trigger delegation flow for re-authorization
        Toast.info(t('payment.customer.changePayment.reauthorizationRequired'));
        connect.open({
          locale: locale as 'en' | 'zh',
          containerEl: undefined as unknown as Element,
          action: 'delegation',
          prefix: joinURL(getPrefix(), '/api/did'),
          saveConnect: false,
          extraParams: { subscriptionId: id },
          messages: {
            scan: t('common.connect.defaultScan'),
            title: t('payment.customer.changePayment.reauthorizationTitle'),
            confirm: t('common.connect.confirm'),
          } as any,
          onSuccess: async () => {
            connect.close();
            Toast.success(t('payment.customer.changePayment.reauthorizationCompleted'));
            await refresh();
          },
          onClose: () => {
            connect.close();
          },
          onError: (err: any) => {
            console.error('Delegation failed:', err);
            Toast.error(formatError(err));
          },
        });
      } else {
        Toast.success(t('common.saved'));
      }
    } catch (err) {
      Toast.error(formatError(err));
    } finally {
      setSlippageSaving(false);
    }
  };

  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 isCredit =
    data?.serviceType === 'credit' ||
    data?.paymentCurrency?.type === 'credit' ||
    data?.items?.some((item) => item?.price?.product?.type === 'credit' || item?.price?.metadata?.credit_config);
  const showOverdraftProtection =
    data?.paymentMethod?.type === 'arcblock' &&
    !overdraftProtectionLoading &&
    !!overdraftProtection &&
    ['active', 'trialing', 'past_due'].includes(data.status) &&
    !isCredit;

  const renderOverdraftProtectionLabel = () => {
    const enabled = data?.overdraft_protection?.enabled;
    const upcomingAmount = overdraftProtection?.upcoming?.amount || '0';
    const gasAmount = overdraftProtection?.gas || '0';
    const insufficient =
      !enableOverdraftProtection ||
      overdraftProtection.unused === '0' ||
      new BN(overdraftProtection.unused).lt(new BN(upcomingAmount).add(new BN(gasAmount)));
    const estimateAmount = +fromUnitToToken(cycleAmount.amount || '0', data.paymentCurrency?.decimal);

    const remainingStake = +fromUnitToToken(overdraftProtection?.unused || '0', data.paymentCurrency?.decimal);
    const formatEstimatedDuration = (cycles: number) => {
      if (!data?.pending_invoice_item_interval) return '';
      const { interval, interval_count: intervalCount } = data.pending_invoice_item_interval;
      const totalIntervals = cycles * intervalCount;
      const availableUnitKeys = ['hour', 'day', 'week', 'month', 'year'];

      if (!availableUnitKeys.includes(interval)) {
        return t('customer.overdraftProtection.estimatedDuration', {
          duration: totalIntervals,
          unit: t('customer.overdraftProtection.intervals').toLowerCase(),
        });
      }
      return t('common.estimatedDuration', {
        duration: formatSmartDuration(totalIntervals, interval as TimeUnit, {
          t,
        }),
      });
    };
    if (!enabled) {
      return (
        <Stack
          direction="row"
          spacing={1}
          sx={{
            alignItems: 'center',
          }}>
          <Typography sx={{ color: 'text.lighter' }}>{t('customer.overdraftProtection.disabled')}</Typography>
          <Button
            size="small"
            sx={{
              fontSize: '13px',
              pt: 0,
              pb: 0,
              height: 3,
              color: 'text.link',
              '&:hover': { backgroundColor: 'primary.lighter' },
            }}
            onClick={() =>
              actionRef.current?.openOverdraftProtection({
                enabled: true,
              })
            }>
            {t('customer.overdraftProtection.open')}
          </Button>
        </Stack>
      );
    }

    if (enabled && insufficient) {
      return (
        <Button
          size="small"
          color="error"
          sx={{
            fontSize: '12px',
            textAlign: 'left',
          }}
          onClick={() =>
            actionRef.current?.openOverdraftProtection({
              enabled: true,
            })
          }>
          {t('customer.overdraftProtection.insufficient')}
        </Button>
      );
    }

    return (
      <Stack
        direction="row"
        sx={{
          alignItems: 'center',
          flexWrap: 'wrap',
          justifyContent: 'flex-end',
          columnGap: 0.5,
        }}>
        <Stack
          direction="row"
          spacing={0.5}
          sx={{
            alignItems: 'center',
          }}>
          <CheckCircle
            sx={{
              fontSize: '16px',
              color: 'success.main',
              verticalAlign: 'middle',
            }}
          />
          <Typography
            sx={{
              color: 'success.main',
              fontWeight: 500,
            }}>
            {t('customer.overdraftProtection.enabled')}
          </Typography>
        </Stack>
        {!isMobile && (
          <Divider
            orientation="vertical"
            flexItem
            sx={{
              mx: 1,
              borderColor: 'divider',
            }}
          />
        )}
        <Typography
          sx={{
            color: 'text.primary',
            display: 'flex',
            alignItems: 'center',
            gap: 0.5,
            fontWeight: 500,
          }}>
          <Avatar src={data.paymentCurrency?.logo} sx={{ width: 16, height: 16 }} alt={data.paymentCurrency?.symbol} />
          <Box
            sx={{
              display: 'flex',
              alignItems: 'baseline',
            }}>
            {formatBNStr(overdraftProtection?.unused, data.paymentCurrency.decimal)}
            <Typography
              sx={{
                color: 'text.secondary',
                fontSize: '14px',
                ml: 0.5,
              }}>
              {data.paymentCurrency.symbol}({formatEstimatedDuration(Math.ceil(remainingStake / estimateAmount))})
            </Typography>
          </Box>
        </Typography>
        {data?.overdraft_protection?.enabled && (
          <Tooltip title={t('customer.overdraftProtection.setting')} placement="top">
            <IconButton
              size="small"
              sx={{
                ml: -1,
                color: 'text.disabled',
                '&:hover': {
                  color: 'primary.main',
                  backgroundColor: 'transparent',
                },
              }}
              onClick={() =>
                actionRef.current?.openOverdraftProtection({
                  enabled: true,
                })
              }>
              <SettingsOutlined fontSize="small" sx={{ fontSize: 16 }} />
            </IconButton>
          </Tooltip>
        )}
      </Stack>
    );
  };

  return (
    <>
      <Root>
        <Box>
          {!(data as any).paymentMethodDetails && ['active', 'trialing'].includes(data.status) && (
            <Alert severity="warning" sx={{ mb: 2 }}>
              {t('admin.subscription.noPaymentMethodWarning')}
            </Alert>
          )}
          {hasUnpaid && (
            <Alert severity="error" sx={{ mb: 2 }}>
              {t('customer.unpaidInvoicesWarningTip')}
            </Alert>
          )}
          {hasPendingAmount && pendingAmount && (
            <Alert severity="error" sx={{ mb: 2 }}>
              {t('customer.pendingAmountWarningTip', {
                amount: formatBNStr(pendingAmount, data?.paymentCurrency?.decimal),
                symbol: data?.paymentCurrency?.symbol,
              })}
            </Alert>
          )}
          <Stack
            className="page-header"
            direction="row"
            sx={{
              justifyContent: 'space-between',
              alignItems: 'center',
              position: 'relative',
            }}>
            {!inArcsphere ? (
              <Stack
                direction="row"
                onClick={() => navigate('/customer', { replace: true })}
                sx={{
                  alignItems: 'center',
                  fontWeight: 'normal',
                  cursor: 'pointer',
                }}>
                <ArrowBackOutlined fontSize="small" sx={{ mr: 0.5, color: 'text.secondary' }} />
                <Typography variant="h6" sx={{ color: 'text.secondary', fontWeight: 'normal' }}>
                  {t('payment.customer.subscriptions.title')}
                </Typography>
              </Stack>
            ) : (
              <Box />
            )}
            <Stack
              direction="row"
              sx={{
                gap: 1,
              }}>
              <SubscriptionActions
                subscription={data}
                onChange={(action) => {
                  refresh();
                  if (action === 'batch-pay') {
                    checkUnpaidInvoices();
                  }
                }}
                showExtra
                showDelegation
                showOverdraftProtection={{
                  show: showOverdraftProtection,
                  onChange: () => refreshOverdraftProtection(),
                }}
                showRecharge
                mode={isMobile ? 'menu-only' : 'primary-buttons'}
                actionProps={{
                  cancel: {
                    variant: 'outlined',
                    color: 'primary',
                  },
                  recover: {
                    variant: 'outlined',
                    color: 'info',
                  },
                  pastDue: {
                    variant: 'outlined',
                    color: 'primary',
                  },
                }}
                setUp={actionSetUp}
              />
            </Stack>
          </Stack>
          <Box
            sx={{
              mt: isMobile ? 2 : 4,
              display: 'flex',
              border: isMobile ? `1px solid ${muiTheme.palette.divider}` : 'none',
              borderRadius: isMobile ? 1 : 0,
              p: isMobile ? 2 : 0,

              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"
              sx={{
                justifyContent: 'space-between',
                alignItems: 'center',
              }}>
              <Stack
                direction="row"
                sx={{
                  alignItems: 'center',
                  flexWrap: 'wrap',
                  gap: 1,
                }}>
                <SubscriptionDescription subscription={data} variant="h1" />
              </Stack>
            </Stack>
            <Stack
              className="section-body"
              sx={{
                justifyContent: 'flex-start',
                flexWrap: 'wrap',
                flex: 1,
                width: '100%',

                'hr.MuiDivider-root:last-child': {
                  display: 'none',
                },

                flexDirection: {
                  xs: 'column',
                  sm: 'column',
                  md: 'row',
                },

                alignItems: 'flex-start',

                gap: {
                  xs: 1,
                  sm: 1,
                  md: 3,
                },
              }}>
              <SubscriptionMetrics subscription={data} />
              {showOverdraftProtection && (
                <InfoMetric
                  label={
                    <Stack
                      direction="row"
                      spacing={0.5}
                      sx={{
                        alignItems: 'center',
                      }}>
                      <Typography
                        component="span"
                        sx={{
                          fontSize: 14,
                          fontWeight: 500,
                        }}>
                        {t('customer.overdraftProtection.title')}
                      </Typography>
                      <MuiLink
                        href="https://www.arcblock.io/content/blog/en/payment-kit-v117-sub-guard#listen-to-the-audio-overview"
                        target="_blank"
                        rel="noopener noreferrer"
                        sx={{
                          display: 'flex',
                          alignItems: 'center',
                        }}>
                        <Tooltip title={t('customer.overdraftProtection.learnMore')} placement="top">
                          <HelpOutline
                            fontSize="small"
                            sx={{
                              fontSize: '14px',
                              ml: -0.2,
                              color: 'text.secondary',
                              cursor: 'pointer',
                              opacity: 0.8,
                              '&:hover': { color: 'primary.main' },
                            }}
                          />
                        </Tooltip>
                      </MuiLink>
                      {data.overdraft_protection?.payment_details?.arcblock?.staking?.address && (
                        <Tooltip
                          title={
                            <Typography sx={{ fontFamily: 'monospace', fontSize: '13px' }}>
                              {t('customer.overdraftProtection.stakingAddress')}：
                              {data.overdraft_protection?.payment_details?.arcblock?.staking?.address}
                            </Typography>
                          }
                          arrow
                          placement="top">
                          <AccountBalanceWalletOutlined
                            sx={{
                              fontSize: '16px',
                              color: 'text.secondary',
                              cursor: 'pointer',
                              ml: 1,
                              '&:hover': { color: 'primary.main' },
                              display: {
                                xs: 'none',
                                md: 'block',
                              },
                            }}
                          />
                        </Tooltip>
                      )}
                    </Stack>
                  }
                  value={renderOverdraftProtectionLabel()}
                />
              )}
              {isCredit && hasPendingAmount && (
                <InfoMetric
                  label={t('admin.customer.creditGrants.pendingAmount')}
                  value={
                    <Typography
                      sx={{
                        color: 'error.main',
                      }}>{`${formatBNStr(pendingAmount, data?.paymentCurrency?.decimal)} ${data?.paymentCurrency?.symbol}`}</Typography>
                  }
                />
              )}
            </Stack>
          </Box>
        </Box>
        {!isMobile ? <Divider /> : null}
        <Box
          className="section"
          sx={{
            containerType: 'inline-size',
            border: isMobile ? `1px solid ${muiTheme.palette.divider}` : 'none',
            borderRadius: isMobile ? 1 : 0,
            p: isMobile ? 2 : 0,
          }}>
          <Typography
            variant="h3"
            className="section-header"
            sx={{
              mb: 3,
            }}>
            {t('admin.details')}
          </Typography>
          <InfoRowGroup
            sx={{
              display: 'grid',
              gridTemplateColumns: {
                xs: 'repeat(1, 1fr)',
                xl: 'repeat(2, 1fr)',
              },
              '@container (min-width: 980px)': {
                gridTemplateColumns: 'repeat(2, 1fr)',
              },
              '.info-row-wrapper': {
                gap: isMobile ? 0.5 : 1,
                flexDirection: {
                  xs: 'column',
                  xl: 'row',
                },
                alignItems: {
                  xs: 'flex-start',
                  xl: 'center',
                },
                '@container (min-width: 980px)': {
                  flexDirection: 'row',
                  alignItems: 'center',
                },
              },
              '.currency-name': {
                color: 'text.secondary',
                lineHeight: 1,
                fontSize: 14,
              },
              '.tx-link-text': {
                fontSize: 14,
                lineHeight: 1,
              },
            }}>
            <InfoRow
              label={t('common.customer')}
              value={<CustomerLink customer={data.customer} linked={false} size="small" />}
            />
            <InfoRow label={t('common.createdAt')} value={formatTime(data.created_at)} />

            <InfoRow
              label={t('admin.subscription.currentPeriod')}
              value={[formatTime(data.current_period_start * 1000), formatTime(data.current_period_end * 1000)].join(
                ' ~ '
              )}
            />
            <InfoRow
              label={t('admin.subscription.trialingPeriod')}
              value={
                data.trial_end && data.trial_start
                  ? [formatTime(data.trial_start * 1000), formatTime(data.trial_end * 1000)].join(' ~ ')
                  : ''
              }
            />
            {data.status === 'paused' && !!data.pause_collection?.resumes_at && (
              <InfoRow label={t('common.resumesAt')} value={formatTime(data.pause_collection.resumes_at * 1000)} />
            )}

            <InfoRow label={t('admin.subscription.collectionMethod')} value={data.collection_method} />

            <InfoRow
              label={t('admin.paymentMethod._name')}
              value={<Currency logo={data.paymentMethod?.logo} name={data.paymentMethod?.name} size={16} />}
            />
            <InfoRow
              label={t('admin.paymentCurrency.name')}
              value={
                <Stack direction="row" spacing={2}>
                  <Currency logo={data.paymentCurrency.logo} name={data.paymentCurrency.symbol} size={16} />
                  {canChangePaymentMethod(data) && (
                    <Button
                      variant="text"
                      sx={{ color: 'text.link' }}
                      size="small"
                      onClick={async () => {
                        // only check unpaid invoices when overdraft protection is enabled
                        if (data?.overdraft_protection?.enabled) {
                          const result = await checkUnpaidInvoices();
                          if (result) {
                            return;
                          }
                        }
                        navigate(`/customer/subscription/${data.id}/change-payment`);
                      }}>
                      {t('payment.customer.subscriptions.changePayment')}
                    </Button>
                  )}
                </Stack>
              }
            />
            {hasDynamicPricing && data.paymentMethod?.type !== 'stripe' && (
              <InfoRow
                label={
                  <Stack direction="row" spacing={0.5} sx={{ alignItems: 'center' }}>
                    <span>{t('common.slippage')}</span>
                    <Tooltip title={t('common.slippageTooltip')} placement="top">
                      <HelpOutline sx={{ fontSize: '0.875rem', color: 'text.secondary', cursor: 'help' }} />
                    </Tooltip>
                  </Stack>
                }
                value={
                  <Stack direction="row" spacing={1} sx={{ alignItems: 'center' }}>
                    <Typography color={displayMinAcceptableRate ? 'text.primary' : 'text.secondary'}>
                      {formatExchangeRateDisplay(displayMinAcceptableRate) || '—'}
                    </Typography>
                    <Button
                      variant="text"
                      size="small"
                      sx={{ color: 'text.link', minWidth: 'auto', p: 0.5 }}
                      onClick={() => setSlippageDialogOpen(true)}
                      disabled={slippageSaving}>
                      <SettingsOutlined sx={{ fontSize: '1rem' }} />
                    </Button>
                  </Stack>
                }
              />
            )}
            <InfoRow
              label={t('admin.subscription.payerAddress')}
              value={
                <PaymentMethodInfo
                  subscriptionId={id}
                  customer={data.customer}
                  paymentMethodDetails={(data as any).paymentMethodDetails}
                  editable={['active', 'trialing', 'past_due'].includes(data.status)}
                  onUpdate={() => {
                    refresh();
                    checkUnpaidInvoices();
                  }}
                  paymentMethodType={data.paymentMethod?.type}
                />
              }
            />

            {data.payment_details && hasDelegateTxHash(data.payment_details, data.paymentMethod) && (
              <InfoRow
                label={t('common.delegateTxHash')}
                value={<TxLink details={data.payment_details} method={data.paymentMethod} size={16} />}
              />
            )}
            {data.paymentMethod?.type === 'arcblock' && data.payment_details?.arcblock?.staking?.tx_hash && (
              <InfoRow
                label={t('common.stakeTxHash')}
                value={
                  <Box
                    sx={{
                      '.MuiTypography-root': {
                        color: 'text.link',
                      },
                    }}>
                    <TxLink
                      details={{ arcblock: { tx_hash: data.payment_details?.arcblock?.staking?.tx_hash, payer: '' } }}
                      method={data.paymentMethod}
                      size={16}
                    />
                  </Box>
                }
              />
            )}
            {!!data.recovered_from && (
              <InfoRow
                label={t('common.recoverFrom')}
                value={
                  <Link to={`/customer/subscription/${data.recovered_from}`} target="_blank">
                    {data.recovered_from}
                  </Link>
                }
              />
            )}
          </InfoRowGroup>
        </Box>
        <Divider />

        {/* Discount Information */}
        {(data as any).discountStats && (
          <Box className="section">
            <Typography variant="h3" className="section-header" sx={{ mb: 1.5 }}>
              {t('admin.subscription.discount')}
            </Typography>
            <Box className="section-body">
              <DiscountInfo discountStats={(data as any).discountStats} />
            </Box>
          </Box>
        )}
        <Box className="divider" />

        <Box className="section">
          <Typography
            variant="h3"
            className="section-header"
            sx={{
              mb: 1.5,
            }}>
            {t('admin.products')}
          </Typography>
          <Box className="section-body">
            <SubscriptionItemList data={data.items} currency={data.paymentCurrency} mode="customer" />
          </Box>
        </Box>
        {(() => {
          const vendorServices = data.items?.map((item) => item.price?.product?.vendor_config || []).flat();

          if (!vendorServices || vendorServices.length === 0) return null;

          return (
            <>
              <Divider />
              <Box className="section">
                <VendorServiceList
                  vendorServices={vendorServices}
                  subscriptionId={id}
                  isCanceled={data.status === 'canceled'}
                />
              </Box>
            </>
          );
        })()}
        <Box className="divider" />
        {isCredit ? (
          <Box className="section">
            <Typography variant="h3" className="section-header">
              {t('admin.creditTransactions.title')}
            </Typography>
            <Box className="section-body">
              <CreditTransactionsList
                customer_id={data.customer_id}
                subscription_id={data.id}
                showAdminColumns={false}
                includeGrants
              />
            </Box>
          </Box>
        ) : (
          <Box className="section">
            <Typography variant="h3" className="section-header">
              {t('customer.invoiceHistory')}
            </Typography>
            <Box className="section-body">
              <CustomerInvoiceList
                subscription_id={data.id}
                type="table"
                include_staking
                status="open,paid,uncollectible,void"
              />
            </Box>
          </Box>
        )}
      </Root>
      <Dialog
        open={slippageDialogOpen}
        onClose={handleSlippageDialogClose}
        maxWidth="xs"
        fullWidth
        PaperProps={{ sx: { borderRadius: 2 } }}>
        <DialogTitle>{t('payment.checkout.quote.slippageLimit.title')}</DialogTitle>
        <DialogContent sx={{ pb: 3 }}>
          <SlippageConfig
            value={slippageConfig.percent}
            onChange={(percent: number) => setSlippageConfig((prev) => ({ ...prev, percent }))}
            config={slippageConfig}
            onConfigChange={setSlippageConfig}
            exchangeRate={liveRateInfo?.rate || null}
            baseCurrency={liveRateInfo?.base_currency || 'USD'}
            disabled={slippageSaving}
            onCancel={handleSlippageDialogClose}
            onSave={handleSlippageSave}
          />
        </DialogContent>
      </Dialog>
    </>
  );
}

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;
    }
  }
`;
