import { useState, useEffect } from 'react';
import { X, CheckCircle, Loader2 } 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';

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 [isComplete, setIsComplete] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // 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 handleBuy = () => {
    setError(null);
    purchaseMutation.mutate(selectedSize, {
      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)}
                      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>

                <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(' ')}
                >
                  {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: selectedSize.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: selectedSize.toLocaleString() })}</p>
                  <p className="text-2xl font-bold text-primary mt-1">
                    {currency.toUpperCase()} {selectedPackage?.price.toFixed(2)}
                  </p>
                </div>

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

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