import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { findCurrency, usePaymentContext } from '@blocklet/payment-react';
import { Box, Typography, Stack } from '@mui/material';
import { styled } from '@mui/system';
import { fromUnitToToken } from '@ocap/util';

const CurrencyRow = styled(Stack)(({ theme }) => ({
  flexDirection: 'row',
  justifyContent: 'space-between',
  alignItems: 'center',
  padding: theme.spacing(1.5, 2),
  backgroundColor: theme.palette.grey[50],
  borderRadius: theme.shape.borderRadius,
  marginBottom: theme.spacing(1),
  '&:last-child': {
    marginBottom: 0,
  },
}));

const CurrencyLabel = styled(Typography)(({ theme }) => ({
  fontWeight: 500,
  color: theme.palette.text.primary,
  textTransform: 'uppercase',
  fontSize: '0.875rem',
}));

const AmountValue = styled(Typography)(({ theme }) => ({
  color: theme.palette.text.secondary,
  fontSize: '0.875rem',
  fontFamily: 'monospace',
}));

const HeaderRow = styled(Stack)(({ theme }) => ({
  flexDirection: 'row',
  justifyContent: 'space-between',
  alignItems: 'center',
  padding: theme.spacing(1, 2),
  marginBottom: theme.spacing(1),
  borderBottom: `1px solid ${theme.palette.divider}`,
}));

const HeaderLabel = styled(Typography)(({ theme }) => ({
  fontWeight: 600,
  color: theme.palette.text.primary,
  fontSize: '0.75rem',
  letterSpacing: '0.5px',
}));

type Props = {
  currencyOptions: Record<string, string | number | { minimum_amount: string } | { amount_off: string }>;
  type?: 'coupon' | 'promotion_code';
};

export default function CurrencyRestrictions({ currencyOptions, type = 'coupon' }: Props) {
  const { t } = useLocaleContext();
  const { settings } = usePaymentContext();

  if (!currencyOptions || Object.keys(currencyOptions).length === 0) {
    return null;
  }

  const currencyEntries = Object.entries(currencyOptions);

  return (
    <Box>
      <HeaderRow>
        <HeaderLabel>{t('admin.coupon.currency')}</HeaderLabel>
        <HeaderLabel>
          {type === 'coupon' ? t('admin.coupon.discountAmount') : t('admin.coupon.minimumAmount')}
        </HeaderLabel>
      </HeaderRow>
      <Stack>
        {currencyEntries.map(([currencyId, data]) => {
          const currency = findCurrency(settings.paymentMethods, currencyId) || {
            id: currencyId,
            symbol: currencyId.toUpperCase(),
            name: currencyId.toUpperCase(),
            decimal: 18,
          };

          // Handle different data formats
          let displayAmount: string;

          if (typeof data === 'string') {
            // Token amount string format (from stored currency_options/restrictions)
            // Convert back to user-friendly display format
            displayAmount = fromUnitToToken(data, currency.decimal);
          } else if (typeof data === 'number') {
            // Direct number format (unit amount) - display as-is
            displayAmount = data.toLocaleString();
          } else if (typeof data === 'object' && data !== null) {
            if ('minimum_amount' in data) {
              // Promotion code format with minimum_amount
              displayAmount = fromUnitToToken((data as { minimum_amount: string }).minimum_amount, currency.decimal);
            } else if ('amount_off' in data) {
              // Coupon format with amount_off (token string)
              displayAmount = fromUnitToToken((data as { amount_off: string }).amount_off, currency.decimal);
            } else {
              // Fallback for unknown object format
              displayAmount = '0';
            }
          } else {
            // Fallback
            displayAmount = '0';
          }

          return (
            <CurrencyRow key={currencyId}>
              <CurrencyLabel>{currency.symbol}</CurrencyLabel>
              <AmountValue>{displayAmount}</AmountValue>
            </CurrencyRow>
          );
        })}
      </Stack>
    </Box>
  );
}
