import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { LockOutlined } from '@mui/icons-material';
import { Box, Typography } from '@mui/material';
import type { TLineItemExpanded, TPaymentCurrency } from '@blocklet/payment-types';
import { useMemo } from 'react';
import { formatExchangeRate } from '../libs/util';

interface QuoteLockInfo {
  exchangeRate: string | null;
  tokenSymbol: string;
  baseCurrency: string;
  expiresAt: number | null;
}

interface QuoteLockBannerProps {
  items: TLineItemExpanded[];
  currency: TPaymentCurrency;
}

function getQuoteLockInfo(items: TLineItemExpanded[], currency: TPaymentCurrency): QuoteLockInfo | null {
  if (!items?.length || !currency) {
    return null;
  }

  const dynamicItems = items.filter((item) => {
    const price = (item.upsell_price || item.price) as any;
    return price?.pricing_type === 'dynamic' && (item as any)?.quoted_amount;
  });
  if (!dynamicItems.length) {
    return null;
  }

  let expiresAt: number | null = null;
  let exchangeRate: string | null = null;

  dynamicItems.forEach((item) => {
    if ((item as any)?.expires_at) {
      expiresAt = expiresAt === null ? (item as any)?.expires_at : Math.min(expiresAt, (item as any)?.expires_at);
    }

    if (!exchangeRate) {
      exchangeRate = (item as any)?.exchange_rate || null;
    }
  });

  return {
    exchangeRate,
    tokenSymbol: currency.symbol,
    baseCurrency: ((dynamicItems[0]?.upsell_price || dynamicItems[0]?.price) as any)?.base_currency || 'USD',
    expiresAt,
  };
}

export default function QuoteLockBanner({ items, currency }: QuoteLockBannerProps) {
  const { t } = useLocaleContext();
  const quoteLockInfo = useMemo(() => getQuoteLockInfo(items, currency), [items, currency]);

  if (!quoteLockInfo || !quoteLockInfo.exchangeRate) {
    return null;
  }

  const formattedRateValue = formatExchangeRate(quoteLockInfo.exchangeRate);
  let formattedRate = '';
  if (formattedRateValue) {
    formattedRate =
      quoteLockInfo.baseCurrency === 'USD'
        ? `$${formattedRateValue}`
        : `${formattedRateValue} ${quoteLockInfo.baseCurrency}`;
  }
  return (
    <Box
      sx={{
        bgcolor: 'action.hover',
        border: '1px solid',
        borderColor: 'divider',
        borderRadius: 1,
        px: 2,
        py: 1.5,
        mb: 2,
      }}>
      <Box
        sx={{
          display: 'flex',
          alignItems: 'center',
          gap: 1.5,
          flexWrap: 'wrap',
        }}>
        <LockOutlined sx={{ fontSize: '1rem', color: 'success.main' }} />
        <Typography sx={{ fontSize: '0.875rem', color: 'text.primary', flex: 1 }}>
          {t('payment.checkout.quote.dynamicPricingInfo', {
            symbol: quoteLockInfo.tokenSymbol,
            rate: formattedRate,
            currency: '',
          })}
        </Typography>
      </Box>
    </Box>
  );
}
