import React, { ReactNode, useEffect } from 'react';
import { useSelector } from 'react-redux';
import { useRouter } from 'next/router';
import Script from 'next/script';

import {
  getUserAccountIdSelector,
  getUserIdSelector,
  getUserRoleSelector,
} from '@/modules/@common/user/redux/selectors';

const GA_TAG = 'G-260ZB3V811';

type Props = {
  children: ReactNode;
};

function GoogleAnalyticsProvider({ children }: Props) {
  const router = useRouter();
  const isProduction = process.env.NODE_ENV === 'production';

  const userId = useSelector(getUserIdSelector);
  const userAccountId = useSelector(getUserAccountIdSelector);
  const { id: roleId, name: roleName, type: roleType } = useSelector(getUserRoleSelector);
  const userEnv = process.env.APP_CONFIG_ENV;

  useEffect(() => {
    const gtagAvailable = typeof window !== 'undefined' && typeof window.gtag === 'function';

    if (isProduction && userId && gtagAvailable) {
      window.gtag('config', GA_TAG);

      window.gtag('set', {
        dimension1: `${userId}`,
        dimension2: `${roleName} (${roleId})`,
        dimension3: roleType,
        dimension4: `${userAccountId}`,
        dimension5: `${userEnv}`,
        location: window.location.href + window.location.hash,
      });

      window.gtag('event', 'pageview');
    }
  }, [router.pathname, userId, roleId, roleName, roleType, userAccountId]);

  return (
    <>
      {isProduction && (
        <>
          <Script src={`https://www.googletagmanager.com/gtag/js?id=${GA_TAG}`} strategy="afterInteractive" />
          <Script id="gtag-init" strategy="afterInteractive">
            {`
              window.dataLayer = window.dataLayer || [];
              function gtag(){dataLayer.push(arguments);}
              gtag('js', new Date());
              gtag('config', '${GA_TAG}');
            `}
          </Script>
        </>
      )}
      {children}
    </>
  );
}

export default GoogleAnalyticsProvider;
