import { useEffect, useState } from 'react';

import { useAuth } from 'src/contexts/JWTContext';
import { UserPermissions } from 'src/utils/permissions';

import usePermissions from './usePermissions';

export const useHuChatbot = () => {
  const { isAuthenticated, instance, user } = useAuth();
  const [isBotOpen, setIsBotOpen] = useState(false);

  const { hasAll: canInteractWithBot } = usePermissions([
    UserPermissions.CAN_INTERACT_WITH_EXTERNAL_BOT,
  ]);

  useEffect(() => {
    if (
      isAuthenticated &&
      instance?.externalBotId &&
      canInteractWithBot &&
      !isBotOpen
    ) {
      const { externalBotId } = instance;
      const script = document.createElement('script');

      // @ts-expect-error
      window.BOTMAKER_VAR = {
        firstName: user?.firstName,
        lastName: user?.lastName,
        businessName: instance.name,
        userId: user?.employeeInternalId,
      };

      script.type = 'text/javascript';
      script.src = `https://go.botmaker.com/rest/webchat/p/${externalBotId}/init.js`;
      script.async = true;

      document.body.appendChild(script);
      setIsBotOpen(true);

      return () => {
        document.body.removeChild(script);
      };
    }
  }, [isAuthenticated]);

  return { isBotOpen, canInteractWithBot };
};
