import { useEffect, useState } 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 { useSubscribe } from '../hooks/useSubscribe';
import { useConfirmSubscription } from '../hooks/useConfirmSubscription';
import { useCompletePayment } from '../hooks/useCompletePayment';
import type { AvailablePlanResponse } from '@/infrastructure/http/api/subscription';

interface PaymentPanelProps {
  plan?: AvailablePlanResponse;
  transactionId?: string;
  /** Pre-created clientSecret — skips API call when provided (e.g. command purchase) */
  directClientSecret?: string;
  /** Override amount display (gross). Used with directClientSecret. */
  displayAmount?: number;
  onClose: () => void;
  onSuccess: () => void;
}

export function PaymentPanel({ plan, transactionId, directClientSecret, displayAmount, onClose, onSuccess }: PaymentPanelProps) {
  const subscribeMutation = useSubscribe();
  const confirmMutation = useConfirmSubscription();
  const completePaymentMutation = useCompletePayment();
  const [isComplete, setIsComplete] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const isTransactionMode = !!transactionId || !!directClientSecret;

  // Initialize payment on mount (skip if directClientSecret provided)
  useEffect(() => {
    if (directClientSecret) return; // PI already created
    if (transactionId) {
      completePaymentMutation.mutate(transactionId!, {
        onError: (err) => setError((err as Error).message || 'Failed to initialize payment'),
      });
    } else if (plan) {
      subscribeMutation.mutate(plan.id, {
        onError: (err) => setError((err as Error).message || 'Failed to initialize payment'),
      });
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [transactionId, plan?.id, directClientSecret]);

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

  const clientSecret = directClientSecret
    ?? (transactionId ? completePaymentMutation.data?.clientSecret : null)
    ?? subscribeMutation.data?.clientSecret;
  const subscriptionId = subscribeMutation.data?.subscriptionId;

  const handleStripeSuccess = (_piId: string) => {
    if (isTransactionMode) {
      // One-time payment — PI succeeded, done
      setIsComplete(true);
    } else if (subscriptionId) {
      // Subscription — confirm with backend
      confirmMutation.mutate(subscriptionId, {
        onSuccess: () => setIsComplete(true),
        onError: (err) => setError((err as Error).message || 'Subscription confirmation failed'),
      });
    }
  };

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

  // Local net→gross (VAT 19%) mirrors @archer/domain netToGross — keeps summary
  // consistent from mount until backend resolves with the authoritative gross amount.
  const planGross = plan?.price != null ? Math.round(plan.price * 1.19 * 100) / 100 : undefined;
  const amount = directClientSecret
    ? displayAmount
    : transactionId
      ? completePaymentMutation.data?.amount
      : subscribeMutation.data?.amount ?? planGross;
  const currency = directClientSecret
    ? 'EUR'
    : transactionId
      ? completePaymentMutation.data?.currency ?? 'EUR'
      : subscribeMutation.data?.currency ?? plan?.currency ?? 'EUR';
  const planName = plan?.title?.en || plan?.slug || 'Payment';
  const priceLabel = amount == null ? '' : amount === 0 ? 'Free' : `\u20AC${amount.toFixed(2)}`;
  const isLoading = directClientSecret ? false : transactionId ? completePaymentMutation.isPending : subscribeMutation.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">Complete Payment</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">Payment Successful</h3>
                <p className="text-sm text-muted-foreground">
                  {isTransactionMode ? 'Your payment has been processed.' : 'Your subscription has been updated.'}
                </p>
              </div>
            ) : (
              <>
                {/* Summary */}
                {(priceLabel || planName !== 'Payment') && (
                  <div className="mb-6 pb-6 border-b border-border">
                    <p className="text-sm text-muted-foreground">{isTransactionMode ? 'Amount due' : 'Selected plan'}</p>
                    {!isTransactionMode && <p className="text-lg font-bold text-foreground">{planName}</p>}
                    {priceLabel && <p className="text-2xl font-bold text-primary mt-1">{priceLabel}</p>}
                  </div>
                )}

                {/* Payment Form */}
                {isLoading ? (
                  <div className="flex flex-col items-center justify-center py-12">
                    <Loader2 className="h-8 w-8 animate-spin text-muted-foreground mb-3" />
                    <p className="text-sm text-muted-foreground">Preparing payment...</p>
                  </div>
                ) : clientSecret && stripePromise ? (
                  <Elements stripe={stripePromise} options={{ clientSecret }}>
                    <StripePaymentForm
                      amount={amount ?? 0}
                      currency={currency}
                      onSuccess={handleStripeSuccess}
                      onError={handleStripeError}
                      isProcessing={isProcessing}
                    />
                  </Elements>
                ) : null}

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