import { decodeEntities } from '@wordpress/html-entities';
import { useEffect, useRef, useState, useCallback } from '@wordpress/element';

const { registerPaymentMethod } = window.wc.wcBlocksRegistry;
const { getSetting } = window.wc.wcSettings;

const settings = getSetting('china_payments_stripe_unionpay_data', {});
const label = decodeEntities(settings.title);

const Icon = () => {
  return settings.icon
    ? <img src={settings.icon} style={{ height: '24px', width: 'auto', maxWidth: '120px', marginLeft: 'auto' }} />
    : '';
};

const Label = () => {
  return (
    <span style={{ width: '100%', display: 'flex', alignItems: 'center' }}>
      {label}
      <Icon />
    </span>
  );
};

const CardElementContent = ({ eventRegistration, emitResponse }) => {
  const cardElementRef = useRef(null);
  const stripeRef = useRef(null);
  const cardMountedRef = useRef(false);
  const [errorMessage, setErrorMessage] = useState('');
  const [isReady, setIsReady] = useState(false);

  // Initialize Stripe and mount Card Element
  useEffect(() => {
    if (cardMountedRef.current) return;

    const publishableKey = settings.stripe_publishable_key;
    if (!publishableKey) {
      setErrorMessage('Stripe configuration error. Please contact the store administrator.');
      console.error('[UnionPay] Missing stripe_publishable_key in settings:', settings);
      return;
    }

    const initStripe = () => {
      if (typeof window.Stripe !== 'function') {
        console.error('[UnionPay] window.Stripe is not a function:', typeof window.Stripe);
        return;
      }

      try {
        stripeRef.current = window.Stripe(publishableKey);

        const elements = stripeRef.current.elements();
        if (!elements) {
          console.error('[UnionPay] stripe.elements() returned falsy');
          return;
        }

        cardElementRef.current = elements.create('card', {
          style: {
            base: {
              fontSize: '16px',
              color: '#32325d',
              fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, sans-serif',
              '::placeholder': {
                color: '#aab7c4',
              },
            },
            invalid: {
              color: '#fa755a',
              iconColor: '#fa755a',
            },
          },
          hidePostalCode: true,
        });

        const mountEl = document.getElementById('china-payments-unionpay-card-element');
        if (mountEl) {
          cardElementRef.current.mount(mountEl);
          cardMountedRef.current = true;
          setIsReady(true);

          cardElementRef.current.on('change', (event) => {
            setErrorMessage(event.error ? event.error.message : '');
          });

          cardElementRef.current.on('ready', () => {
            console.log('[UnionPay] Card Element ready');
          });
        } else {
          console.error('[UnionPay] Mount element not found');
        }
      } catch (err) {
        console.error('[UnionPay] Error initializing Stripe:', err);
        setErrorMessage('Failed to initialize payment form. Please refresh the page.');
      }
    };

    // Stripe.js should already be loaded as a script dependency,
    // but add a fallback polling mechanism just in case
    if (typeof window.Stripe === 'function') {
      initStripe();
    } else {
      let attempts = 0;
      const interval = setInterval(() => {
        attempts++;
        if (typeof window.Stripe === 'function') {
          clearInterval(interval);
          initStripe();
        } else if (attempts > 50) {
          clearInterval(interval);
          console.error('[UnionPay] Stripe.js failed to load after 10 seconds');
          setErrorMessage('Payment system failed to load. Please refresh the page.');
        }
      }, 200);
      return () => clearInterval(interval);
    }
  }, []);

  // Register payment processing handler
  useEffect(() => {
    const unsubscribe = eventRegistration.onPaymentSetup(() => {
      if (!cardMountedRef.current) {
        return {
          type: emitResponse.responseTypes.ERROR,
          message: 'Card element not ready. Please wait and try again.',
        };
      }
      return {
        type: emitResponse.responseTypes.SUCCESS,
        meta: {},
      };
    });

    return unsubscribe;
  }, [eventRegistration, emitResponse]);

  // Intercept checkout success to confirm card payment before redirect
  useEffect(() => {
    const unsubscribe = eventRegistration.onCheckoutSuccess(async ({ redirectUrl }) => {
      // Only handle our custom inline card confirmation URLs
      if (!redirectUrl || !redirectUrl.includes('china-payments-confirm-card')) {
        return { type: emitResponse.responseTypes.SUCCESS };
      }

      const url = new URL(redirectUrl);
      const clientSecret = url.searchParams.get('china-payments-intent-secret');
      const returnUrl = url.searchParams.get('china-payments-return');

      if (!clientSecret) {
        console.error('[UnionPay] Missing client secret in redirect URL');
        return { type: emitResponse.responseTypes.SUCCESS };
      }

      if (!stripeRef.current || !cardElementRef.current) {
        console.error('[UnionPay] Stripe not initialized for payment confirmation');
        return {
          type: emitResponse.responseTypes.ERROR,
          message: 'Payment form not ready. Please refresh and try again.',
        };
      }

      try {
        const result = await stripeRef.current.confirmCardPayment(clientSecret, {
          payment_method: {
            card: cardElementRef.current,
          },
        });

        if (result.error) {
          return {
            type: emitResponse.responseTypes.ERROR,
            message: result.error.message,
          };
        }

        if (result.paymentIntent && result.paymentIntent.status === 'succeeded') {
          // Payment confirmed! Redirect through server-side verification endpoint
          // (same flow as WeChat Pay / Alipay — verifies PI and calls payment_complete)
          const paymentCompletedBaseUrl = settings.payment_completed_url || '';
          const decodedReturnUrl = returnUrl ? decodeURIComponent(returnUrl) : '';
          const orderIdMatch = decodedReturnUrl.match(/order-received\/(\d+)/);
          const orderId = orderIdMatch ? orderIdMatch[1] : '';

          if (paymentCompletedBaseUrl && orderId) {
            return {
              type: emitResponse.responseTypes.SUCCESS,
              redirectUrl: paymentCompletedBaseUrl + orderId,
            };
          }

          // Fallback: direct redirect to order-received page
          return {
            type: emitResponse.responseTypes.SUCCESS,
            redirectUrl: decodedReturnUrl || redirectUrl.split('?')[0],
          };
        }

        return {
          type: emitResponse.responseTypes.ERROR,
          message: 'Payment was not completed. Please try again.',
        };
      } catch (err) {
        console.error('[UnionPay] Payment confirmation error:', err);
        return {
          type: emitResponse.responseTypes.ERROR,
          message: err.message || 'An unexpected error occurred.',
        };
      }
    });

    return unsubscribe;
  }, [eventRegistration, emitResponse]);

  return (
    <div style={{ padding: '10px 0' }}>
      <div
        id="china-payments-unionpay-card-element"
        style={{
          padding: '12px',
          border: '1px solid #e0e0e0',
          borderRadius: '6px',
          background: '#fff',
          minHeight: '24px',
        }}
      ></div>
      {errorMessage && (
        <div style={{ color: '#fa755a', fontSize: '13px', marginTop: '8px' }}>
          {errorMessage}
        </div>
      )}
    </div>
  );
};

registerPaymentMethod({
  name: 'china_payments_stripe_unionpay',
  label: <Label />,
  content: <CardElementContent />,
  edit: <div>{decodeEntities(settings.description || '')}</div>,
  canMakePayment: () => true,
  ariaLabel: label,
  supports: {
    features: settings.supports,
  },
});
