/**
 * TotalSection Component
 *
 * Displays total amount, USD equivalent, exchange rate details,
 * and quote information for dynamic pricing.
 */

import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import type { TPaymentCurrency } from '@blocklet/payment-types';
import { Box, Skeleton, Stack, Tooltip, Typography } from '@mui/material';
import PaymentAmount from '../amount';
import QuoteDetailsPanel from '../../components/quote-details-panel';
import type { SlippageConfigValue } from '../../components/slippage-config';

export interface RateInfo {
  exchangeRate: string | null;
  baseCurrency: string;
  providerName?: string | null;
  providerId?: string | null;
  timestampMs?: number | null;
}

export interface QuoteDetailRow {
  label: string;
  value: string | React.ReactNode;
  isSlippage?: boolean;
}

export interface TotalSectionProps {
  totalAmountText: string;
  totalUsdDisplay: string | null;
  currency: TPaymentCurrency;
  hasDynamicPricing: boolean;
  rateDisplay: string | null;
  rateInfo: RateInfo;
  quoteDetailRows: QuoteDetailRow[];
  currentSlippagePercent: number;
  slippageConfig?: SlippageConfigValue;
  isPriceLocked: boolean;
  isSubscription: boolean;
  completed?: boolean;
  onSlippageChange?: (slippageConfig: SlippageConfigValue) => void;
  isStripePayment?: boolean;
  thenInfo?: string;
  isRateLoading?: boolean; // Loading state for skeleton display during currency switch
}

export default function TotalSection({
  totalAmountText,
  totalUsdDisplay,
  currency,
  hasDynamicPricing,
  rateDisplay,
  rateInfo,
  quoteDetailRows,
  currentSlippagePercent,
  slippageConfig = undefined,
  isPriceLocked,
  isSubscription,
  completed = false,
  onSlippageChange = undefined,
  isStripePayment = false,
  thenInfo = '',
  isRateLoading = false,
}: TotalSectionProps) {
  const { t } = useLocaleContext();

  return (
    <>
      <Stack
        sx={{
          display: 'flex',
          justifyContent: 'space-between',
          flexDirection: 'row',
          alignItems: 'flex-start',
          width: '100%',
        }}>
        <Box className="base-label">{t('common.total')}</Box>
        <Stack sx={{ alignItems: 'flex-end' }}>
          {isRateLoading ? (
            <Skeleton variant="text" width={100} height={24} />
          ) : (
            <PaymentAmount amount={totalAmountText} sx={{ fontSize: '16px' }} />
          )}

          {/* USD equivalent display - hide for Stripe payments since base_amount is already USD */}
          {/* No skeleton for USD - it's based on base_amount which doesn't change */}
          {hasDynamicPricing &&
            !isStripePayment &&
            !isRateLoading &&
            (totalUsdDisplay ? (
              <Typography sx={{ fontSize: '0.7875rem', color: 'text.lighter' }}>≈ ${totalUsdDisplay}</Typography>
            ) : (
              <Tooltip title={t('payment.checkout.quote.referenceUnavailable')} placement="top">
                <Box component="span">
                  <Typography sx={{ fontSize: '0.7875rem', color: 'text.lighter' }}>≈ —</Typography>
                </Box>
              </Tooltip>
            ))}

          {/* Quote details panel for dynamic pricing - hide for Stripe payments since no exchange rate conversion needed */}
          {/* Show panel if hasDynamicPricing is true, even without rateDisplay (for metered subscriptions waiting for first usage) */}
          {hasDynamicPricing && !isStripePayment && (
            <QuoteDetailsPanel
              rateLine={
                rateDisplay ? t('payment.checkout.quote.rateLine', { symbol: currency.symbol, rate: rateDisplay }) : ''
              }
              rows={quoteDetailRows}
              isSubscription={isSubscription}
              slippageValue={currentSlippagePercent}
              slippageConfig={slippageConfig}
              onSlippageChange={!completed && onSlippageChange ? onSlippageChange : undefined}
              exchangeRate={rateInfo.exchangeRate}
              baseCurrency={rateInfo.baseCurrency}
              disabled={isPriceLocked}
            />
          )}

          {/* Lock expired warning removed - per Final Freeze design, Quote doesn't expire by time */}
        </Stack>
      </Stack>
      {thenInfo && (
        <Stack
          sx={{
            display: 'flex',
            justifyContent: 'space-between',
            flexDirection: 'row',
            alignItems: 'flex-start',
            width: '100%',
            borderTop: '1px solid',
            borderColor: 'divider',
            pt: 1,
            mt: 1,
          }}>
          <Box className="base-label">{t('common.nextCharge')}</Box>
          <Typography sx={{ fontSize: '16px', color: 'text.secondary' }}>{thenInfo}</Typography>
        </Stack>
      )}
    </>
  );
}
