import React, { useEffect, useRef } from 'react';
import { usePaddle } from './PaddleProvider';

interface SubscribeButtonProps {
  priceId: string;
  children: React.ReactNode;
  className?: string;
  onSuccess?: (data: any) => void;
  onCancel?: () => void;
  disabled?: boolean;
  customData?: Record<string, any>;
}

export const SubscribeButton: React.FC<SubscribeButtonProps> = ({ 
  priceId, 
  children, 
  className,
  onSuccess,
  onCancel,
  disabled,
  customData
}) => {
  const { paddle, isLoading, registerEventCallback } = usePaddle();

  // Use refs to always have the latest callbacks without re-registering
  const onSuccessRef = useRef(onSuccess);
  const onCancelRef = useRef(onCancel);

  // Keep refs up to date on every render
  useEffect(() => {
    onSuccessRef.current = onSuccess;
    onCancelRef.current = onCancel;
  });

  // Register a stable event callback once on mount, unregister on unmount
  useEffect(() => {
    console.log('[SubscribeButton] Registering paddle event callback');

    registerEventCallback((event: any) => {
      console.log('[SubscribeButton] Event received:', event.name, event.data);
      if (event.name === 'checkout.completed') {
        console.log('[SubscribeButton] checkout.completed → calling onSuccess');
        onSuccessRef.current?.(event.data);
      } else if (event.name === 'checkout.closed') {
        console.log('[SubscribeButton] checkout.closed → calling onCancel');
        onCancelRef.current?.();
      }
    });

    return () => {
      console.log('[SubscribeButton] Unregistering paddle event callback');
      registerEventCallback(null);
    };
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [registerEventCallback]);

  const handleCheckout = () => {
    if (!paddle || !priceId || disabled || isLoading) {
      console.warn('[SubscribeButton] Cannot open checkout:', { paddle: !!paddle, priceId, disabled, isLoading });
      return;
    }

    console.log('[SubscribeButton] Opening checkout for priceId:', priceId);
    paddle.Checkout.open({
      items: [
        {
          priceId: priceId,
          quantity: 1,
        },
      ],
      customData: customData,
      settings: {
        displayMode: 'overlay',
        theme: 'light',
        locale: 'fr',
      }
    });
  };

  return (
    <button
      onClick={handleCheckout}
      disabled={isLoading || !paddle || disabled}
      className={`${className} ${(isLoading || !paddle || disabled) ? 'opacity-50 cursor-not-allowed' : ''}`}
    >
      {isLoading ? (
        <span className="flex items-center gap-2">
          <div className="w-4 h-4 border-2 border-current border-t-transparent rounded-full animate-spin" />
          Chargement...
        </span>
      ) : children}
    </button>
  );
};
