import AddShoppingCartIcon from '@mui/icons-material/AddShoppingCart';
import ShoppingCartCheckoutIcon from '@mui/icons-material/ShoppingCartCheckout';
import { Avatar, Box, Button, Chip, Stack, Typography } from '@mui/material';
import type { TPaymentCurrency, TPrice } from '@blocklet/payment-types';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { formatDynamicUnitPrice, tSafe, INTERVAL_LOCALE_KEY, primaryContrastColor } from '../../utils/format';

interface CrossSellCardProps {
  crossSellItem: TPrice;
  currency: TPaymentCurrency | null;
  exchangeRate: string | null;
  crossSellRequired: boolean;
  onAdd: () => Promise<void>;
}

export default function CrossSellCard({
  crossSellItem,
  currency,
  exchangeRate,
  crossSellRequired,
  onAdd,
}: CrossSellCardProps) {
  const { t } = useLocaleContext();
  if (!crossSellItem) return null;

  const { product } = crossSellItem as any;
  const productImage = product?.images?.[0] || '';
  const productName = product?.name || t('payment.checkout.cross_sell.add');
  const { recurring } = crossSellItem as any;
  const intervalKey = recurring?.interval ? INTERVAL_LOCALE_KEY[recurring.interval] : null;
  // Show interval label (e.g. "monthly") instead of description when description repeats title
  const rawDescription = product?.description || '';
  const subtitle = (() => {
    if (rawDescription && rawDescription !== productName) return rawDescription;
    return intervalKey ? t(intervalKey) : '';
  })();

  return (
    <Box sx={{ position: 'relative' }}>
      {/* Recommended badge — top-right, matching product-item-card */}
      {crossSellRequired && (
        <Chip
          label={tSafe(t, 'payment.checkout.cross_sell.recommended', 'RECOMMENDED')}
          size="small"
          sx={{
            position: 'absolute',
            top: 0,
            right: 40,
            transform: 'translateY(-50%)',
            zIndex: 1,
            height: 22,
            fontSize: 9,
            fontWeight: 900,
            letterSpacing: '0.12em',
            bgcolor: 'primary.main',
            color: (theme: any) => primaryContrastColor(theme),
            boxShadow: '0 4px 12px rgba(45,124,243,0.2)',
            '& .MuiChip-label': { px: 1.5 },
          }}
        />
      )}

      <Box
        sx={{
          p: { xs: 2, md: 3 },
          bgcolor: 'background.paper',
          borderRadius: { xs: '16px', md: '24px' },
          border: '2px dashed',
          borderColor: (theme) => (theme.palette.mode === 'dark' ? 'rgba(255,255,255,0.15)' : 'rgba(45,124,243,0.25)'),
          boxShadow: (theme) =>
            theme.palette.mode === 'dark' ? '0 12px 40px -8px rgba(0,0,0,0.3)' : '0 12px 40px -8px rgba(0,0,0,0.06)',
          transition: 'all 0.3s ease',
          cursor: 'pointer',
          '&:hover': {
            borderColor: 'primary.main',
            boxShadow: '0 12px 40px -8px rgba(0,0,0,0.1)',
          },
        }}
        onClick={onAdd}>
        <Stack direction="row" spacing={{ xs: 1.5, md: 2.5 }} sx={{ alignItems: 'center', width: '100%' }}>
          {/* Product avatar */}
          {productImage ? (
            <Avatar
              src={productImage}
              variant="rounded"
              sx={{
                width: { xs: 44, md: 64 },
                height: { xs: 44, md: 64 },
                borderRadius: { xs: '12px', md: '16px' },
                flexShrink: 0,
              }}
            />
          ) : (
            <Avatar
              variant="rounded"
              sx={{
                width: { xs: 44, md: 64 },
                height: { xs: 44, md: 64 },
                borderRadius: { xs: '12px', md: '16px' },
                bgcolor: (theme) => (theme.palette.mode === 'dark' ? 'rgba(255,255,255,0.06)' : '#eff6ff'),
                flexShrink: 0,
              }}>
              <ShoppingCartCheckoutIcon sx={{ fontSize: { xs: 22, md: 28 }, color: 'primary.main', opacity: 0.45 }} />
            </Avatar>
          )}

          <Box sx={{ flex: 1, minWidth: 0 }}>
            <Stack direction="row" justifyContent="space-between" alignItems="flex-start" sx={{ mb: 0.25 }}>
              <Typography
                sx={{ fontWeight: 800, fontSize: { xs: 15, md: 18 }, color: 'text.primary', lineHeight: 1.3 }}>
                {productName}
              </Typography>
              <Stack alignItems="flex-end" sx={{ flexShrink: 0, ml: { xs: 1, md: 2 } }}>
                <Typography
                  sx={{ fontWeight: 800, color: 'text.primary', whiteSpace: 'nowrap', fontSize: { xs: 15, md: 18 } }}>
                  {formatDynamicUnitPrice(crossSellItem as any, currency, exchangeRate)} {currency?.symbol}
                </Typography>
                {exchangeRate && (crossSellItem as any).base_amount && (
                  <Typography sx={{ fontSize: 10, color: 'text.disabled', fontWeight: 700, lineHeight: 1 }}>
                    ≈ ${Number((crossSellItem as any).base_amount || 0).toFixed(2)}
                  </Typography>
                )}
              </Stack>
            </Stack>
            {subtitle && (
              <Typography
                sx={{ fontSize: { xs: 12, md: 14 }, color: 'text.secondary', fontWeight: 500, lineHeight: 1.4 }}
                noWrap>
                {subtitle}
              </Typography>
            )}

            <Box sx={{ pt: { xs: 1.5, md: 2 } }}>
              <Button
                size="small"
                variant="outlined"
                startIcon={<AddShoppingCartIcon sx={{ fontSize: '14px !important' }} />}
                sx={{
                  textTransform: 'none',
                  fontSize: { xs: 11, md: 12 },
                  fontWeight: 700,
                  borderRadius: '8px',
                  border: '1px solid',
                  borderColor: 'divider',
                  color: 'primary.main',
                  bgcolor: 'background.paper',
                  boxShadow: 1,
                  px: 1.5,
                  py: 0.5,
                  transition: 'all 0.2s',
                  '&:hover': {
                    bgcolor: 'primary.main',
                    color: (theme: any) => primaryContrastColor(theme),
                    borderColor: 'primary.main',
                  },
                  '&:active': { transform: 'scale(0.95)' },
                }}
                onClick={(e) => {
                  e.stopPropagation();
                  onAdd();
                }}>
                {tSafe(t, 'payment.checkout.cross_sell.addToOrder', 'Add to order')}
              </Button>
            </Box>
          </Box>
        </Stack>
      </Box>
    </Box>
  );
}
