import { useState } from 'react';
import AddIcon from '@mui/icons-material/Add';
import CloseIcon from '@mui/icons-material/Close';
import LocalOfferIcon from '@mui/icons-material/LocalOffer';
import {
  Alert,
  Box,
  Button,
  CircularProgress,
  IconButton,
  InputAdornment,
  Skeleton,
  Stack,
  TextField,
  Typography,
} from '@mui/material';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';

interface PromotionInputProps {
  promotion: {
    applied: boolean;
    code: string | null;
    active: boolean;
    inactiveReason: string | null;
    apply: (code: string) => Promise<{ success: boolean; error?: string }>;
    remove: () => Promise<void>;
  };
  discounts: any[];
  discountAmount: string | null;
  /** Start with input field visible (skip the "Add promotion code" button) */
  initialShowInput?: boolean;
  /** Show skeleton for the discount amount while switching */
  isAmountLoading?: boolean;
}

export default function PromotionInput({
  promotion,
  discounts,
  discountAmount,
  initialShowInput = false,
  isAmountLoading = false,
}: PromotionInputProps) {
  const { t } = useLocaleContext();
  const [showInput, setShowInput] = useState(false);
  const [code, setCode] = useState('');
  const [applying, setApplying] = useState(false);
  const [error, setError] = useState('');

  // When initialShowInput is true, always show the input (e.g. inside a drawer)
  const effectiveShowInput = initialShowInput || showInput;

  const handleApply = async () => {
    if (!code.trim()) return;
    setApplying(true);
    setError('');
    const result = await promotion.apply(code.trim());
    if (!result.success) {
      setError(result.error || 'Invalid code');
    } else {
      setCode('');
      setShowInput(false);
    }
    setApplying(false);
  };

  const handleKeyPress = (event: React.KeyboardEvent) => {
    if (event.key === 'Enter' && !applying && code.trim()) {
      handleApply();
    }
  };

  // Display applied discounts
  if (discounts?.length > 0) {
    return (
      <Box>
        {discounts.map((disc: any, i: number) => {
          const discCode =
            disc.promotion_code_details?.code || disc.verification_data?.code || disc.promotion_code || '';
          const coupon = disc.coupon_details || {};
          const couponOff =
            coupon.percent_off > 0
              ? t('payment.checkout.coupon.percentage', { percent: coupon.percent_off })
              : `${coupon.percent_off || 0}%`;
          let description = '';
          if (coupon.duration === 'repeating' && coupon.duration_in_months) {
            const months = coupon.duration_in_months;
            description = `${couponOff} for ${months} month${months > 1 ? 's' : ''}`;
          } else if (coupon.duration === 'forever') {
            description = t('payment.checkout.coupon.terms.forever', { couponOff });
          } else if (coupon.duration === 'once') {
            description = t('payment.checkout.coupon.terms.once', { couponOff });
          }
          return (
            <Stack
              key={disc.promotion_code || disc.coupon || i}
              direction="row"
              justifyContent="space-between"
              alignItems="center">
              <Stack
                direction="row"
                alignItems="center"
                spacing={0.5}
                sx={{
                  bgcolor: (theme) => (theme.palette.mode === 'dark' ? 'rgba(18,184,134,0.1)' : '#ebfef5'),
                  px: 1.5,
                  py: 0.5,
                  borderRadius: '8px',
                  border: '1px solid',
                  borderColor: (theme) => (theme.palette.mode === 'dark' ? 'rgba(18,184,134,0.2)' : '#d3f9e8'),
                }}>
                <LocalOfferIcon sx={{ color: '#12b886', fontSize: 14 }} />
                <Typography sx={{ fontWeight: 700, fontSize: 13, color: '#12b886' }}>{discCode}</Typography>
                {description && (
                  <Typography sx={{ fontSize: 12, color: '#12b886', fontWeight: 500, opacity: 0.8 }}>
                    · {description}
                  </Typography>
                )}
                <IconButton size="small" onClick={promotion.remove} sx={{ width: 18, height: 18, ml: 0.25 }}>
                  <CloseIcon sx={{ fontSize: 12, color: '#12b886' }} />
                </IconButton>
              </Stack>
              {isAmountLoading ? (
                <Skeleton variant="text" width={80} height={22} />
              ) : (
                <Typography sx={{ color: 'text.primary', fontWeight: 600, fontSize: 14 }}>
                  -{discountAmount || '0'}
                </Typography>
              )}
            </Stack>
          );
        })}
      </Box>
    );
  }

  // Add promo code — consistent height: button and input share same container height
  if (!promotion.active) return null;

  return (
    <Box sx={{ minHeight: 36 }}>
      {effectiveShowInput ? (
        <Box
          onBlur={(e) => {
            // Don't collapse if initialShowInput is forced (e.g. inside a drawer)
            if (initialShowInput) return;
            if (!e.currentTarget.contains(e.relatedTarget as Node) && !code.trim()) {
              setShowInput(false);
            }
          }}>
          <TextField
            fullWidth
            size="small"
            value={code}
            onChange={(e) => setCode(e.target.value)}
            onKeyPress={handleKeyPress}
            placeholder={t('payment.checkout.promotion.placeholder')}
            disabled={applying}
            autoFocus
            slotProps={{
              input: {
                endAdornment: (
                  <InputAdornment position="end">
                    <Button
                      size="small"
                      onClick={handleApply}
                      disabled={!code.trim() || applying}
                      variant="text"
                      sx={{
                        color: 'primary.main',
                        fontSize: 13,
                        textTransform: 'none',
                        minWidth: 'auto',
                        fontWeight: 600,
                      }}>
                      {applying ? <CircularProgress size={16} /> : t('payment.checkout.promotion.apply')}
                    </Button>
                  </InputAdornment>
                ),
              },
            }}
            sx={{
              '& .MuiOutlinedInput-root': { pr: 1, borderRadius: '8px', height: 36 },
              '& .MuiOutlinedInput-input': { py: '6px', fontSize: 13 },
            }}
          />
          {error && (
            <Alert severity="error" sx={{ mt: 0.5, py: 0, fontSize: 12, borderRadius: '6px' }}>
              {error}
            </Alert>
          )}
        </Box>
      ) : (
        <Button
          onClick={() => setShowInput(true)}
          startIcon={<AddIcon sx={{ fontSize: 18 }} />}
          variant="text"
          sx={{
            fontWeight: 600,
            fontSize: 13,
            textTransform: 'none',
            justifyContent: 'flex-start',
            p: 0,
            height: 36,
            color: 'primary.main',
            '&:hover': {
              backgroundColor: 'transparent',
              textDecoration: 'underline',
            },
          }}>
          {t('payment.checkout.promotion.add_code')}
        </Button>
      )}
    </Box>
  );
}
