import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import { useSelector } from 'react-redux';
import { useRouter } from 'next/router';
import { OpenWithRounded } from '@mui/icons-material';

import {
  getIntercomUserHashSelector,
  getUserAccountIdSelector,
  getUserAccountSelector,
  getUserEmailSelector,
  getUserFullNameSelector,
  getUserRoleSelector,
} from '@/modules/@common/user/redux/selectors';

import ViewportDraggable from '@/modules/@common/ViewportDraggable/ViewportDraggable';
import { Button } from '@/mui/components';
import { CustomIntercomChat } from '@/mui/components/CustomIcon';

import styles from './IntercomProvider.module.scss';

const intercomComponentId = 'custom_intercom_launcher_id';

function IntercomProvider(props) {
  const router = useRouter();
  const [intercomInitialized, setIntercomInitialized] = useState(false);
  const [intercomBooted, setIntercomBooted] = useState(false);
  const intercomKey = process.env.APP_INTERCOM_KEY;
  const intercomExcludePaths = process.env.APP_INTERCOM_EXCLUDE_PATHS.split(',');

  const userRole = useSelector(getUserRoleSelector);
  const userEmail = useSelector(getUserEmailSelector);
  const userFullName = useSelector(getUserFullNameSelector);
  const userAccount = useSelector(getUserAccountSelector);
  const userAccountId = useSelector(getUserAccountIdSelector);
  const userHash = useSelector(getIntercomUserHashSelector);

  const bootIntercom = () => {
    window.Intercom('boot', {
      app_id: intercomKey,
      hide_default_launcher: true,
      custom_launcher_selector: `#${intercomComponentId}`,
      api_base: 'https://api-iam.intercom.io',
      email: userEmail,
      user_hash: userHash || '',
      name: userFullName,
      role: `${userRole?.name}`,
      company: {
        company_id: userAccountId,
        name: `${userAccount?.name}`,
        type: `${userAccount?.type}`,
      },
    });
    setIntercomBooted(true);
  };

  const shutdownIntercom = () => {
    window.Intercom('shutdown');
    setIntercomBooted(false);
  };

  useEffect(() => {
    if (intercomInitialized) {
      if (intercomBooted && intercomExcludePaths.some((path) => router?.asPath.split('?')[0].includes(path))) {
        shutdownIntercom();
      }
      if (
        userAccountId &&
        !intercomBooted &&
        !intercomExcludePaths.some((path) => router?.asPath.split('?')[0].includes(path))
      ) {
        bootIntercom();
      }
    }
  }, [router]);

  useEffect(() => {
    if (intercomKey) {
      (function () {
        const w = window;
        const ic = w.Intercom;
        if (typeof ic === 'function') {
          ic('reattach_activator');
          ic('update', w.intercomSettings);
        } else {
          const d = document;
          // eslint-disable-next-line func-style
          const i = function () {
            // eslint-disable-next-line prefer-rest-params
            i.c(arguments);
          };
          i.q = [];
          i.c = function (args) {
            i.q.push(args);
          };
          w.Intercom = i;
          // eslint-disable-next-line func-style
          const l = function () {
            const s = d.createElement('script');
            s.type = 'text/javascript';
            s.async = true;
            s.src = `https://widget.intercom.io/widget/${intercomKey}`;
            const x = d.getElementsByTagName('script')[0];
            x.parentNode.insertBefore(s, x);
          };
          if (document.readyState === 'complete') {
            l();
          } else if (w.attachEvent) {
            w.attachEvent('onload', l);
          } else {
            w.addEventListener('load', l, false);
          }
        }
      })();
      setIntercomInitialized(true);
    }
  }, [intercomKey]);

  useEffect(() => {
    if (
      userAccountId &&
      intercomKey &&
      intercomInitialized &&
      !intercomExcludePaths.some((path) => router?.asPath.split('?')[0].includes(path))
    ) {
      bootIntercom();
    }
  }, [intercomInitialized]);

  return (
    <>
      {props.children}
      {intercomBooted && (
        <ViewportDraggable className={styles.Wrapper}>
          <Button
            square
            color="neutral"
            size="xSmall"
            shape="circular"
            startIcon={<OpenWithRounded />}
            className={styles.Drag}
          />
          <div id={intercomComponentId} className={styles.Button}>
            <CustomIntercomChat fontSize="x2Large" />
          </div>
        </ViewportDraggable>
      )}
    </>
  );
}

IntercomProvider.propTypes = {
  children: PropTypes.node.isRequired,
};

export default IntercomProvider;
