import { useState, useEffect, useMemo } from 'react';
import { X, CheckCircle, Loader2, Minus, Plus } from 'lucide-react';
import { Elements } from '@stripe/react-stripe-js';
import { StripePaymentForm } from './StripePaymentForm';
import { stripePromise } from '@/infrastructure/stripe';
import { usePurchaseCommands } from '../hooks/usePurchaseCommands';
import { useConfirmCommandPurchase } from '../hooks/useConfirmCommandPurchase';
import { useTranslation } from '@/i18n/TranslationProvider';

const MIN_QTY = 1;
const MAX_QTY = 100;

interface CommandPackage {
  size: 100 | 1000;
  price: number;
}

interface CommandPurchasePanelProps {
  packages: CommandPackage[];
  currency: string;
  onClose: () => void;
  onSuccess: () => void;
}

export function CommandPurchasePanel({ packages, currency, onClose, onSuccess }: CommandPurchasePanelProps) {
  const { t } = useTranslation();
  const purchaseMutation = usePurchaseCommands();
  const confirmMutation = useConfirmCommandPurchase();
  const [selectedSize, setSelectedSize] = useState<100 | 1000>(packages[0]?.size ?? 100);
  const [quantity, setQuantity] = useState<number>(1);
  const [isComplete, setIsComplete] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const clampQty = (n: number) => Math.max(MIN_QTY, Math.min(MAX_QTY, Math.floor(n)));

  // Auto-close after success
  useEffect(() => {
    if (!isComplete) return;
    const timer = setTimeout(() => {
      onSuccess();
      onClose();
    }, 2000);
    return () => clearTimeout(timer);
  }, [isComplete, onSuccess, onClose]);

  const selectedPackage = packages.find((p) => p.size === selectedSize);
  const clientSecret = purchaseMutation.data?.clientSecret;

  const totals = useMemo(() => {
    const packPrice = selectedPackage?.price ?? 0;
    return {
      commands: selectedSize * quantity,
      cost: Number((packPrice * quantity).toFixed(2)),
    };
  }, [selectedSize, quantity, selectedPackage?.price]);

  const handleBuy = () => {
    setError(null);
    purchaseMutation.mutate({ packageSize: selectedSize, quantity }, {
      onError: (err) => setError((err as Error).message || 'Failed to initialize payment'),
    });
  };

  const handleStripeSuccess = (paymentIntentId: string) => {
    confirmMutation.mutate(paymentIntentId, {
      onSuccess: () => setIsComplete(true),
      onError: (err) => setError((err as Error).message || 'Purchase confirmation failed'),
    });
  };

  const handleStripeError = (msg: string) => {
    setError(msg);
  };

  const isLoading = purchaseMutation.isPending;
  const isProcessing = confirmMutation.isPending;

  return (
    <>
      {/* Backdrop */}
      <div
        className="fixed inset-0 bg-black/50 z-40 transition-opacity animate-fade-in"
        onClick={onClose}
        aria-hidden="true"
      />

      {/* Modal */}
      <div className="fixed inset-0 z-50 flex items-center justify-center p-4 pointer-events-none">
        <div
          className="bg-card rounded-2xl border border-border shadow-2xl w-full max-w-md pointer-events-auto animate-scale-in"
          onClick={(e) => e.stopPropagation()}
        >
          {/* Header */}
          <div className="flex items-center justify-between p-6 border-b border-border">
            <h2 className="text-xl font-semibold text-foreground">{t('subscription.buyCommands')}</h2>
            <button
              onClick={onClose}
              className="p-2 hover:bg-muted rounded-lg transition-colors"
              aria-label="Close"
            >
              <X className="w-5 h-5 text-muted-foreground" />
            </button>
          </div>

          {/* Body */}
          <div className="p-6">
            {isComplete ? (
              <div className="flex flex-col items-center text-center py-8">
                <CheckCircle className="h-16 w-16 text-green-500 mb-4" />
                <h3 className="text-xl font-bold text-foreground mb-2">{t('subscription.commandsAdded')}</h3>
                <p className="text-sm text-muted-foreground">
                  {t('subscription.commandsAvailable')}
                </p>
              </div>
            ) : !clientSecret ? (
              <>
                {/* Package Selection */}
                <div className="space-y-3 mb-6">
                  <p className="text-sm text-muted-foreground">{t('subscription.selectPackage')}</p>
                  {packages.map((pkg) => (
                    <button
                      key={pkg.size}
                      onClick={() => { setSelectedSize(pkg.size); setQuantity(1); }}
                      className={[
                        'w-full flex items-center justify-between p-4 rounded-xl border-2 transition-colors',
                        selectedSize === pkg.size
                          ? 'border-primary bg-primary/5'
                          : 'border-border hover:border-muted-foreground/30',
                      ].join(' ')}
                    >
                      <div className="text-left">
                        <p className="text-lg font-bold text-foreground">{t('subscription.nCommands', { count: pkg.size.toLocaleString() })}</p>
                        <p className="text-sm text-muted-foreground">
                          {currency.toUpperCase()} {(pkg.price / pkg.size).toFixed(2)} {t('subscription.perCommand')}
                        </p>
                      </div>
                      <p className="text-xl font-bold text-primary">
                        {currency.toUpperCase()} {pkg.price.toFixed(2)}
                      </p>
                    </button>
                  ))}
                </div>

                {/* Qty stepper + totals */}
                <div className="mb-6 rounded-xl border-2 border-border p-4">
                  <div className="flex items-center justify-between mb-3">
                    <p className="text-sm text-muted-foreground">{t('subscription.qty')}</p>
                    <div className="inline-flex items-center gap-2">
                      <button
                        type="button"
                        aria-label={t('subscription.decrease')}
                        onClick={() => setQuantity((q) => clampQty(q - 1))}
                        disabled={quantity <= MIN_QTY}
                        className="h-8 w-8 inline-flex items-center justify-center rounded-md border border-border hover:bg-muted disabled:opacity-40"
                      >
                        <Minus className="w-4 h-4" />
                      </button>
                      <input
                        type="number"
                        min={MIN_QTY}
                        max={MAX_QTY}
                        value={quantity}
                        onChange={(e) => setQuantity(clampQty(Number(e.target.value) || 1))}
                        className="w-14 h-8 text-center rounded-md border border-border bg-background text-foreground"
                        aria-label={t('subscription.qty')}
                      />
                      <button
                        type="button"
                        aria-label={t('subscription.increase')}
                        onClick={() => setQuantity((q) => clampQty(q + 1))}
                        disabled={quantity >= MAX_QTY}
                        className="h-8 w-8 inline-flex items-center justify-center rounded-md border border-border hover:bg-muted disabled:opacity-40"
                      >
                        <Plus className="w-4 h-4" />
                      </button>
                    </div>
                  </div>
                  <div className="flex items-center justify-between text-sm">
                    <span className="text-muted-foreground">{t('subscription.totalCommands')}</span>
                    <span className="font-semibold text-foreground" data-testid="cmd-total-commands">{totals.commands.toLocaleString()}</span>
                  </div>
                  <div className="flex items-center justify-between text-base mt-1">
                    <span className="text-muted-foreground">{t('subscription.totalCost')}</span>
                    <span className="font-bold text-primary" data-testid="cmd-total-cost">
                      {currency.toUpperCase()} {totals.cost.toFixed(2)}
                    </span>
                  </div>
                </div>

                <button
                  onClick={handleBuy}
                  disabled={isLoading || !selectedPackage}
                  className={[
                    'w-full rounded-lg px-4 py-3 text-sm font-semibold text-white transition-colors',
                    'focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500',
                    isLoading
                      ? 'cursor-not-allowed bg-gray-400'
                      : 'bg-blue-600 hover:bg-blue-700',
                  ].join(' ')}
                  data-testid="cmd-buy"
                >
                  {isLoading ? (
                    <span className="flex items-center justify-center gap-2">
                      <Loader2 className="h-4 w-4 animate-spin" />
                      {t('subscription.preparingPayment')}
                    </span>
                  ) : (
                    t('subscription.buyNCommands', { count: totals.commands.toLocaleString() })
                  )}
                </button>

                {error && (
                  <p className="mt-3 text-sm text-destructive">{error}</p>
                )}
              </>
            ) : (
              <>
                {/* Stripe Payment Form */}
                <div className="mb-6 pb-6 border-b border-border">
                  <p className="text-sm text-muted-foreground">{t('subscription.package')}</p>
                  <p className="text-lg font-bold text-foreground">
                    {t('subscription.nCommands', { count: totals.commands.toLocaleString() })}
                    <span className="text-sm font-normal text-muted-foreground"> ({quantity} × {selectedSize})</span>
                  </p>
                  <p className="text-2xl font-bold text-primary mt-1">
                    {currency.toUpperCase()} {totals.cost.toFixed(2)}
                  </p>
                </div>

                {stripePromise ? (
                  <Elements stripe={stripePromise} options={{ clientSecret }}>
                    <StripePaymentForm
                      amount={totals.cost}
                      currency={currency}
                      onSuccess={handleStripeSuccess}
                      onError={handleStripeError}
                      isProcessing={isProcessing}
                      submitLabel={t('subscription.buyNCommands', { count: totals.commands.toLocaleString() })}
                    />
                  </Elements>
                ) : null}

                {error && (
                  <p className="mt-3 text-sm text-destructive">{error}</p>
                )}
              </>
            )}
          </div>
        </div>
      </div>
    </>
  );
}
