import { Box, Typography, Stack } from '@mui/material';
import { LocalOfferOutlined } from '@mui/icons-material';
import { formatTime, formatAmount, findCurrency, usePaymentContext, useMobile } from '@blocklet/payment-react';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';

type DiscountStats = {
  subscription_id: string;
  total_discount_records: number;
  total_savings: Record<
    string,
    {
      amount: string;
      currency: any;
      formattedAmount: string;
    }
  >;
  coupons_used: string[];
  promotion_codes_used: any[];
  discount_records: any[];
};

type DiscountInfoProps = {
  discountStats?: DiscountStats | null;
};

export default function DiscountInfo({ discountStats = null }: DiscountInfoProps) {
  const { t } = useLocaleContext();
  const { settings } = usePaymentContext();
  const { isMobile } = useMobile();

  if (!discountStats || discountStats.total_discount_records === 0) {
    return null;
  }

  // Get primary coupon info
  const primaryRecord = discountStats.discount_records?.[0];
  const coupon = primaryRecord?.coupon;

  if (!coupon) {
    return null;
  }

  // Use coupon name instead of promotion code
  const couponName = coupon.name || t('admin.coupon.discount');

  // Format discount type
  const getDiscountType = () => {
    if (coupon.percent_off && coupon.percent_off > 0) {
      return t('admin.coupon.couponTermsPercentage', { percent: coupon.percent_off });
    }
    if (coupon.amount_off && coupon.amount_off !== '0') {
      const currency = findCurrency(settings.paymentMethods, coupon.currency_id) || settings.baseCurrency;
      return t('admin.coupon.couponTermsFixedAmount', {
        amount: formatAmount(coupon.amount_off, currency.decimal),
        symbol: currency.symbol,
      });
    }
    return t('admin.coupon.noDiscount');
  };

  // Format duration
  const getDuration = () => {
    if (coupon.duration === 'repeating' && coupon.duration_in_months) {
      return t(`admin.coupon.couponTermsDuration.${coupon.duration}`, { months: coupon.duration_in_months });
    }
    return t(`admin.coupon.couponTermsDuration.${coupon.duration}`);
  };

  // Format total savings with proper decimal precision
  const totalSavingsEntries = Object.entries(discountStats.total_savings);
  const savingsText =
    totalSavingsEntries.length > 0
      ? totalSavingsEntries
          .map(([, savings]) => {
            // Use formatAmount to properly format with decimal precision
            const formatted = formatAmount(savings.amount, savings.currency?.decimal || 18);
            return `${formatted} ${savings.currency?.symbol || ''}`;
          })
          .join(', ')
      : '--';

  // Get validity period
  const getValidityPeriod = () => {
    if (coupon.duration !== 'repeating') {
      return '';
    }
    if (primaryRecord?.discount_start && primaryRecord?.discount_end) {
      const startDate = formatTime(primaryRecord.discount_start * 1000);
      const endDate = formatTime(primaryRecord.discount_end * 1000);
      return `${startDate} ~ ${endDate}`;
    }
    return '';
  };

  return (
    <Box
      sx={{
        bgcolor: 'grey.50',
        borderRadius: 1.5,
        p: 2.5,
        border: '1px solid',
        borderColor: 'divider',
      }}>
      <Stack spacing={1}>
        <Stack
          direction={isMobile ? 'column' : 'row'}
          spacing={2}
          sx={{
            alignItems: isMobile ? 'flex-start' : 'center',
          }}>
          <Stack
            direction="row"
            spacing={1}
            sx={{
              alignItems: 'center',
              flex: 1,
            }}>
            <LocalOfferOutlined sx={{ color: 'primary.main', fontSize: 20 }} />
            <Typography variant="subtitle2" sx={{ fontWeight: 600, color: 'text.primary' }}>
              {couponName}
            </Typography>
          </Stack>

          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
            <Typography variant="body2" sx={{ fontWeight: 500, color: 'text.secondary' }}>
              {getDiscountType()}
            </Typography>
            {getDuration() && (
              <>
                <Typography
                  variant="body2"
                  sx={{
                    color: 'text.disabled',
                  }}>
                  |
                </Typography>
                <Typography
                  variant="body2"
                  sx={{
                    color: 'text.secondary',
                  }}>
                  {getDuration()}
                </Typography>
              </>
            )}
          </Box>
        </Stack>

        <Stack
          direction={isMobile ? 'column' : 'row'}
          spacing={2}
          sx={{
            alignItems: isMobile ? 'flex-start' : 'center',
          }}>
          <Box sx={{ flex: 1 }}>
            <Typography
              variant="body2"
              sx={{
                color: 'text.secondary',
              }}>
              {t('admin.discount.totalSaved')}:{' '}
              <Typography component="span" sx={{ color: 'success.main', fontWeight: 600, ml: 0.5 }}>
                {savingsText}
              </Typography>
            </Typography>
          </Box>

          {getValidityPeriod() && (
            <Box>
              <Typography
                variant="body2"
                sx={{
                  color: 'text.primary',
                }}>
                {t('admin.coupon.discountPeriod')}: {getValidityPeriod()}
              </Typography>
            </Box>
          )}
        </Stack>
      </Stack>
    </Box>
  );
}
