'use client';

import React, { useState, useEffect } from 'react';
import { 
  Elements, 
  CardElement, 
  useStripe, 
  useElements,
  PaymentElement 
} from '@stripe/react-stripe-js';
import { useToast } from '@/components/ui/ToastContext';
import getStripe, { stripeElementsOptions } from '@/lib/stripe-client';
import './StripePaymentForm.css';

interface PaymentFormProps {
  clientSecret: string;
  amount: number;
  currency: string;
  onSuccess: (paymentIntent: any) => void;
  onError: (error: string) => void;
  onProcessing?: (isProcessing: boolean) => void;
}

interface StripePaymentFormProps {
  clientSecret: string;
  amount: number;
  currency: string;
  categoryNames: string[];
  onSuccess: (paymentIntent: any) => void;
  onError: (error: string) => void;
  onCancel?: () => void;
}

// Payment form component that uses Stripe Elements
function PaymentForm({ 
  clientSecret, 
  amount, 
  currency, 
  onSuccess, 
  onError,
  onProcessing 
}: PaymentFormProps) {
  const stripe = useStripe();
  const elements = useElements();
  const [isLoading, setIsLoading] = useState(false);
  const [errorMessage, setErrorMessage] = useState<string>('');
  const [isElementReady, setIsElementReady] = useState(false);
  useEffect(() => {
    // Safety timeout: if element doesn't become ready, surface a helpful message
    if (!isElementReady) {
      const t = setTimeout(() => {
        if (!isElementReady) {
          const msg = 'Payment form is taking longer than expected to load. Please refresh and try again.';
          setErrorMessage(msg);
        }
      }, 6000);
      return () => clearTimeout(t);
    }
  }, [isElementReady]);
  const { showError, showSuccess } = useToast();

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

    if (!stripe || !elements) {
      const errorMsg = 'Stripe payment system is not ready yet. Please wait a moment and try again.';
      setErrorMessage(errorMsg);
      showError(errorMsg, 'Payment System Loading');
      return;
    }

    // Ensure PaymentElement is mounted and ready
    const paymentElement = elements.getElement(PaymentElement);
    if (!paymentElement) {
      const errorMsg = 'Payment form is not fully loaded yet. Please wait a moment and try again.';
      setErrorMessage(errorMsg);
      showError(errorMsg, 'Payment Form Loading');
      return;
    }

    setIsLoading(true);
    setErrorMessage('');
    onProcessing?.(true);
    // showSuccess('Processing your payment securely...', 'Payment Processing');

    try {
      // Confirm payment with Stripe
      // Confirm payment with mounted Payment Element
      const { error, paymentIntent } = await stripe.confirmPayment({
        elements,
        confirmParams: {
          return_url: `${window.location.origin}/freelancer/membership/success`
        },
        redirect: 'if_required',
      });

      if (error) {
        let userMessage = 'An error occurred during payment processing.';
        
        // Provide more specific error messages based on error type
        if (error.type === 'card_error') {
          switch (error.code) {
            case 'card_declined':
              userMessage = 'Your card was declined. Please check your card details or try a different payment method.';
              break;
            case 'insufficient_funds':
              userMessage = 'Your card has insufficient funds. Please try a different payment method.';
              break;
            case 'expired_card':
              userMessage = 'Your card has expired. Please use a different payment method.';
              break;
            case 'incorrect_cvc':
              userMessage = 'The security code (CVC) you entered is incorrect. Please check and try again.';
              break;
            case 'processing_error':
              userMessage = 'An error occurred while processing your card. Please try again in a few minutes.';
              break;
            default:
              userMessage = error.message || 'Your card could not be processed. Please check your details and try again.';
          }
        } else if (error.type === 'validation_error') {
          userMessage = 'Please check your payment information and try again.';
        } else if (error.type === 'api_connection_error') {
          userMessage = 'Network connection error. Please check your internet connection and try again.';
        } else if (error.type === 'rate_limit_error') {
          userMessage = 'Too many requests. Please wait a moment and try again.';
        } else {
          userMessage = error.message || userMessage;
        }
        
        setErrorMessage(userMessage);
        onError(userMessage);
        showError(userMessage, 'Payment Failed');
        
        console.error('Stripe payment error:', {
          type: error.type,
          code: error.code,
          message: error.message,
          decline_code: error.decline_code
        });
      } else if (paymentIntent && paymentIntent.status === 'succeeded') {
        showSuccess('🎉 Payment successful! Processing your membership activation...', 'Payment Completed');
        onSuccess(paymentIntent);
      } else if (paymentIntent && paymentIntent.status === 'requires_action') {
        // Handle 3D Secure or other authentication
        const authMessage = 'Your payment requires additional authentication. Please complete the verification process that should appear shortly.';
        setErrorMessage(authMessage);
        showError(authMessage, 'Additional Authentication Required');
        console.warn('Payment requires additional authentication:', paymentIntent);
      } else if (paymentIntent && paymentIntent.status === 'processing') {
        const processingMessage = 'Your payment is being processed. This may take a few moments.';
        setErrorMessage(processingMessage);
        showSuccess(processingMessage, 'Payment Processing');
        console.info('Payment is processing:', paymentIntent);
      } else {
        const incompleteMessage = 'Payment was not completed successfully. Please try again or contact support if the issue persists.';
        setErrorMessage(incompleteMessage);
        onError(incompleteMessage);
        showError(incompleteMessage, 'Payment Incomplete');
        console.error('Payment not completed:', paymentIntent);
      }
    } catch (err: any) {
      const message = err?.message || 'An unexpected error occurred during payment processing. Please try again.';
      setErrorMessage(message);
      onError(message);
      showError(`Unexpected error: ${message}. If this continues, please contact support.`, 'Payment System Error');
      console.error('Unexpected payment error:', err);
    } finally {
      setIsLoading(false);
      onProcessing?.(false);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="stripe-payment-form">
      <div className="payment-amount-display">
        <h4>Payment Summary</h4>
        <div className="amount-row">
          <span>Total Amount:</span>
          <span className="amount">
            {(() => {
              // Debug: log the amount to understand the format
              console.log('Payment amount received:', amount, 'Currency:', currency);
              
              // Amount is now passed as actual value (not cents) from the server
              const displayAmount = amount;
              
              return new Intl.NumberFormat('en-US', {
                style: 'currency',
                currency: currency,
              }).format(displayAmount);
            })()}
          </span>
        </div>
      </div>

      <div className="payment-element-container">
        <PaymentElement 
          options={{
            layout: 'tabs',
            defaultValues: {
              billingDetails: {
                email: '',
              },
            },
            // Indian regulations compliance: name and address must be collected for exports
            fields: {
              billingDetails: 'auto'
            }
          }}
          onReady={() => setIsElementReady(true)}
          onChange={() => { if (errorMessage) setErrorMessage(''); }}
        />
      </div>

      {errorMessage && (
        <div className="stripe-error-message">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M12 9V13M12 17H12.01M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z" stroke="#ef4444" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
          {errorMessage}
        </div>
      )}

      <div className="stripe-form-actions">
        <button
          type="submit"
          disabled={!stripe || !elements || !isElementReady || isLoading}
          className="stripe-pay-button"
        >
          {isLoading ? (
            <>
              <div className="spinner"></div>
              Processing...
            </>
          ) : (
            <>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M9 12L11 14L15 10M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
              Complete Payment
            </>
          )}
        </button>
      </div>

      <div className="stripe-security-notice">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
        Your payment information is secure and encrypted.
      </div>
    </form>
  );
}

// Main component that wraps the payment form with Stripe Elements
export default function StripePaymentForm({ 
  clientSecret, 
  amount, 
  currency, 
  categoryNames,
  onSuccess, 
  onError,
  onCancel 
}: StripePaymentFormProps) {
  const [stripePromise] = useState(() => getStripe());
  const { showError, showSuccess } = useToast();

  if (!clientSecret) {
    return (
      <div className="stripe-loading">
        <div className="spinner"></div>
        <p>Loading secure payment form...</p>
      </div>
    );
  }

  const elementsOptions = {
    clientSecret,
    appearance: stripeElementsOptions.appearance,
    loader: stripeElementsOptions.loader,
  };

  return (
    <div className="stripe-payment-container">
      <div className="stripe-payment-header">
        <h3>Complete Your Membership Purchase</h3>
        <p>You are purchasing membership for: <strong>{categoryNames.join(', ')}</strong></p>
      </div>

      <Elements stripe={stripePromise} options={elementsOptions}>
        <PaymentForm
          clientSecret={clientSecret}
          amount={amount}
          currency={currency}
          onSuccess={onSuccess}
          onError={onError}
          onProcessing={(isProcessing) => {
            if (isProcessing) {
              showSuccess('Securely processing your payment. Please do not close this window.', 'Processing Payment');
            }
          }}
        />
      </Elements>

      {onCancel && (
        <div className="stripe-cancel-action">
          <button 
            onClick={() => {
              showSuccess('Payment cancelled. You can try again anytime.', 'Payment Cancelled');
              onCancel();
            }}
            className="stripe-cancel-button"
            type="button"
          >
            Cancel Payment
          </button>
        </div>
      )}

      <div className="stripe-powered-by">
        <span>Powered by</span>
        <svg width="32" height="14" viewBox="0 0 60 25" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path fillRule="evenodd" clipRule="evenodd" d="M59.5 12.5c0-6.904-5.596-12.5-12.5-12.5s-12.5 5.596-12.5 12.5 5.596 12.5 12.5 12.5 12.5-5.596 12.5-12.5zm-12.5-10c5.523 0 10 4.477 10 10s-4.477 10-10 10-10-4.477-10-10 4.477-10 10-10z" fill="#6772e5"/>
          <path d="M22.5 8.5h15v8h-15v-8z" fill="#6772e5"/>
          <path d="M0 8.5h15v8h-15v-8z" fill="#6772e5"/>
        </svg>
      </div>
    </div>
  );
}