/**
 * Credit Payment Form Component
 *
 * Uses Stripe Elements for secure card collection when purchasing
 * communication credits.
 */

import React, { useState, useEffect } from 'react';
import { loadStripe } from '@stripe/stripe-js';
import {
  Elements,
  PaymentElement,
  useStripe,
  useElements,
} from '@stripe/react-stripe-js';
import { CreditCard, Loader2, X, CheckCircle, AlertCircle } from 'lucide-react';
import { useCreatePaymentIntent, useConfirmPayment } from '../hooks/useCommunicationCredits';

// Initialize Stripe
const stripePromise = loadStripe(import.meta.env.VITE_STRIPE_PUBLISHABLE_KEY || '');

interface PaymentFormProps {
  amountCents: number;
  onSuccess: () => void;
  onCancel: () => void;
  savePaymentMethod?: boolean;
}

const PaymentFormInner: React.FC<PaymentFormProps> = ({
  amountCents,
  onSuccess,
  onCancel,
  savePaymentMethod = false,
}) => {
  const stripe = useStripe();
  const elements = useElements();
  const [isProcessing, setIsProcessing] = useState(false);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  const [isComplete, setIsComplete] = useState(false);
  const [isElementReady, setIsElementReady] = useState(false);
  const confirmPayment = useConfirmPayment();

  const formatCurrency = (cents: number) => `$${(cents / 100).toFixed(2)}`;

  const handleSubmit = async (event: React.FormEvent) => {
    event.preventDefault();

    if (!stripe || !elements) {
      return;
    }

    setIsProcessing(true);
    setErrorMessage(null);

    try {
      // Confirm the payment with Stripe
      const { error, paymentIntent } = await stripe.confirmPayment({
        elements,
        confirmParams: {
          return_url: window.location.href,
        },
        redirect: 'if_required',
      });

      if (error) {
        setErrorMessage(error.message || 'Payment failed. Please try again.');
        setIsProcessing(false);
        return;
      }

      if (paymentIntent && paymentIntent.status === 'succeeded') {
        // Confirm the payment on the backend
        await confirmPayment.mutateAsync({
          payment_intent_id: paymentIntent.id,
          save_payment_method: savePaymentMethod,
        });
        setIsComplete(true);
        setTimeout(() => {
          onSuccess();
        }, 1500);
      }
    } catch (err: any) {
      setErrorMessage(err.message || 'An unexpected error occurred.');
      setIsProcessing(false);
    }
  };

  if (isComplete) {
    return (
      <div className="text-center py-8">
        <CheckCircle className="w-16 h-16 text-green-500 mx-auto mb-4" />
        <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-2">
          Payment Successful!
        </h3>
        <p className="text-gray-600 dark:text-gray-400">
          {formatCurrency(amountCents)} has been added to your credits.
        </p>
      </div>
    );
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <div className="bg-gray-50 dark:bg-gray-700/50 rounded-lg p-4 mb-4">
        <div className="flex justify-between items-center">
          <span className="text-gray-600 dark:text-gray-400">Amount</span>
          <span className="text-xl font-bold text-gray-900 dark:text-white">
            {formatCurrency(amountCents)}
          </span>
        </div>
      </div>

      <div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4">
        {!isElementReady && (
          <div className="flex items-center justify-center py-8">
            <Loader2 className="w-6 h-6 animate-spin text-gray-400" />
            <span className="ml-2 text-sm text-gray-500 dark:text-gray-400">Loading payment form...</span>
          </div>
        )}
        <div className={isElementReady ? '' : 'hidden'}>
          <PaymentElement
            onReady={() => setIsElementReady(true)}
            options={{
              layout: 'tabs',
            }}
          />
        </div>
      </div>

      {errorMessage && (
        <div className="flex items-start gap-2 p-3 bg-red-50 dark:bg-red-900/30 border border-red-200 dark:border-red-800 rounded-lg">
          <AlertCircle className="w-5 h-5 text-red-600 dark:text-red-400 shrink-0 mt-0.5" />
          <p className="text-sm text-red-600 dark:text-red-400">{errorMessage}</p>
        </div>
      )}

      <div className="flex gap-3 pt-2">
        <button
          type="button"
          onClick={onCancel}
          disabled={isProcessing}
          className="flex-1 py-2.5 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-50"
        >
          Cancel
        </button>
        <button
          type="submit"
          disabled={!stripe || isProcessing}
          className="flex-1 py-2.5 bg-brand-600 text-white rounded-lg hover:bg-brand-700 disabled:opacity-50 flex items-center justify-center gap-2"
        >
          {isProcessing ? (
            <>
              <Loader2 className="w-4 h-4 animate-spin" />
              Processing...
            </>
          ) : (
            <>
              <CreditCard className="w-4 h-4" />
              Pay {formatCurrency(amountCents)}
            </>
          )}
        </button>
      </div>

      <p className="text-xs text-center text-gray-500 dark:text-gray-400 mt-2">
        Your payment is securely processed by Stripe
      </p>
    </form>
  );
};

interface CreditPaymentModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess: () => void;
  amountCents: number;
  onAmountChange?: (cents: number) => void;
  savePaymentMethod?: boolean;
  skipAmountSelection?: boolean;
}

export const CreditPaymentModal: React.FC<CreditPaymentModalProps> = ({
  isOpen,
  onClose,
  onSuccess,
  amountCents,
  onAmountChange,
  savePaymentMethod = false,
  skipAmountSelection = false,
}) => {
  const [clientSecret, setClientSecret] = useState<string | null>(null);
  const [isLoadingIntent, setIsLoadingIntent] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [showPaymentForm, setShowPaymentForm] = useState(false);
  const [autoInitialized, setAutoInitialized] = useState(false);
  const createPaymentIntent = useCreatePaymentIntent();

  const formatCurrency = (cents: number) => `$${(cents / 100).toFixed(2)}`;

  useEffect(() => {
    if (!isOpen) {
      setClientSecret(null);
      setShowPaymentForm(false);
      setError(null);
      setAutoInitialized(false);
    }
  }, [isOpen]);

  // Auto-initialize payment when skipping amount selection
  useEffect(() => {
    if (isOpen && skipAmountSelection && !autoInitialized && !isLoadingIntent && !clientSecret) {
      setAutoInitialized(true);
      handleContinueToPayment();
    }
  }, [isOpen, skipAmountSelection, autoInitialized, isLoadingIntent, clientSecret]);

  const handleContinueToPayment = async () => {
    setIsLoadingIntent(true);
    setError(null);

    try {
      const result = await createPaymentIntent.mutateAsync(amountCents);
      setClientSecret(result.client_secret);
      setShowPaymentForm(true);
    } catch (err: any) {
      setError(err.response?.data?.error || 'Failed to initialize payment. Please try again.');
    } finally {
      setIsLoadingIntent(false);
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-lg p-6">
        <div className="flex items-center justify-between mb-4">
          <div>
            <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
              {skipAmountSelection ? 'Complete Payment' : 'Add Credits'}
            </h3>
            <p className="text-sm text-gray-500 dark:text-gray-400">
              {skipAmountSelection
                ? `Loading ${formatCurrency(amountCents)} to your balance`
                : 'Choose an amount to add to your balance'
              }
            </p>
          </div>
          <button
            onClick={onClose}
            className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Loading state when auto-initializing */}
        {skipAmountSelection && isLoadingIntent && !clientSecret ? (
          <div className="flex flex-col items-center justify-center py-12">
            <Loader2 className="w-8 h-8 animate-spin text-brand-600 mb-4" />
            <p className="text-gray-600 dark:text-gray-400">Setting up payment...</p>
          </div>
        ) : skipAmountSelection && error && !clientSecret ? (
          <div className="space-y-4">
            <div className="flex items-start gap-2 p-3 bg-red-50 dark:bg-red-900/30 border border-red-200 dark:border-red-800 rounded-lg">
              <AlertCircle className="w-5 h-5 text-red-600 dark:text-red-400 shrink-0 mt-0.5" />
              <p className="text-sm text-red-600 dark:text-red-400">{error}</p>
            </div>
            <div className="flex gap-3">
              <button
                onClick={onClose}
                className="flex-1 py-2 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700"
              >
                Cancel
              </button>
              <button
                onClick={() => {
                  setAutoInitialized(false);
                  setError(null);
                }}
                className="flex-1 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700"
              >
                Try Again
              </button>
            </div>
          </div>
        ) : !showPaymentForm && !skipAmountSelection ? (
          <div className="space-y-4">
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              Quick select
            </label>
            <div className="grid grid-cols-3 gap-3">
              {[1000, 2500, 5000].map((amount) => (
                <button
                  key={amount}
                  onClick={() => onAmountChange?.(amount)}
                  className={`py-3 px-4 rounded-lg border-2 transition-colors ${
                    amountCents === amount
                      ? 'border-brand-600 bg-brand-50 dark:bg-brand-900/30 text-brand-600'
                      : 'border-gray-200 dark:border-gray-700 hover:border-gray-300'
                  }`}
                >
                  <span className="font-semibold">{formatCurrency(amount)}</span>
                </button>
              ))}
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Custom amount (whole dollars only)
              </label>
              <div className="relative">
                <span className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-900 dark:text-white font-medium">$</span>
                <input
                  type="text"
                  inputMode="numeric"
                  pattern="[0-9]*"
                  value={amountCents / 100}
                  onChange={(e) => {
                    const val = e.target.value.replace(/[^0-9]/g, '');
                    onAmountChange?.(Math.max(5, parseInt(val) || 5) * 100);
                  }}
                  onKeyDown={(e) => {
                    if (!/[0-9]/.test(e.key) && !['Backspace', 'Delete', 'ArrowLeft', 'ArrowRight', 'Tab'].includes(e.key)) {
                      e.preventDefault();
                    }
                  }}
                  className="w-full pl-8 pr-12 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                />
                <span className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 dark:text-gray-500">.00</span>
              </div>
            </div>

            {error && (
              <div className="flex items-start gap-2 p-3 bg-red-50 dark:bg-red-900/30 border border-red-200 dark:border-red-800 rounded-lg">
                <AlertCircle className="w-5 h-5 text-red-600 dark:text-red-400 shrink-0 mt-0.5" />
                <p className="text-sm text-red-600 dark:text-red-400">{error}</p>
              </div>
            )}

            <div className="flex gap-3 pt-4">
              <button
                onClick={onClose}
                className="flex-1 py-2 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700"
              >
                Cancel
              </button>
              <button
                onClick={handleContinueToPayment}
                disabled={isLoadingIntent}
                className="flex-1 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 disabled:opacity-50 flex items-center justify-center gap-2"
              >
                {isLoadingIntent ? (
                  <>
                    <Loader2 className="w-4 h-4 animate-spin" />
                    Loading...
                  </>
                ) : (
                  <>
                    <CreditCard className="w-4 h-4" />
                    Continue to Payment
                  </>
                )}
              </button>
            </div>
          </div>
        ) : clientSecret ? (
          <Elements
            stripe={stripePromise}
            options={{
              clientSecret,
              appearance: {
                theme: 'stripe',
                variables: {
                  colorPrimary: '#2563eb',
                  colorBackground: '#ffffff',
                  colorText: '#1e293b',
                  colorDanger: '#dc2626',
                  fontFamily: 'system-ui, -apple-system, sans-serif',
                  spacingUnit: '12px',
                  borderRadius: '8px',
                },
              },
            }}
          >
            <PaymentFormInner
              amountCents={amountCents}
              onSuccess={onSuccess}
              onCancel={() => {
                setShowPaymentForm(false);
                setClientSecret(null);
              }}
              savePaymentMethod={savePaymentMethod}
            />
          </Elements>
        ) : null}
      </div>
    </div>
  );
};

export default CreditPaymentModal;
