/**
 * GlobalSubscriptionHandler - Listens for subscription errors and shows upgrade dialogs
 */

import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { subscriptionErrorEmitter, SubscriptionError } from '../../api/client/apiClient';
import SubscriptionErrorHandler from './SubscriptionErrorHandler';

const GlobalSubscriptionHandler: React.FC = () => {
  const [subscriptionError, setSubscriptionError] = useState<SubscriptionError | null>(null);
  const [showErrorDialog, setShowErrorDialog] = useState(false);
  const navigate = useNavigate();

  useEffect(() => {
    const handleSubscriptionError = (event: CustomEvent<SubscriptionError>) => {
      setSubscriptionError(event.detail);
      setShowErrorDialog(true);
    };

    subscriptionErrorEmitter.addEventListener(
      'subscriptionError',
      handleSubscriptionError as EventListener
    );

    return () => {
      subscriptionErrorEmitter.removeEventListener(
        'subscriptionError',
        handleSubscriptionError as EventListener
      );
    };
  }, []);

  const handleClose = () => {
    setShowErrorDialog(false);
    setSubscriptionError(null);
  };

  const handleUpgrade = () => {
    setShowErrorDialog(false);
    setSubscriptionError(null);
    navigate('/app/settings/profile');
  };

  if (!subscriptionError) {
    return null;
  }

  return (
    <SubscriptionErrorHandler
      error={subscriptionError}
      isOpen={showErrorDialog}
      onClose={handleClose}
      onUpgrade={handleUpgrade}
    />
  );
};

export default GlobalSubscriptionHandler;
export { GlobalSubscriptionHandler };