import { useEffect } from 'react';
import Script from 'next/script';

import type { MappedUser } from '~/src/lib/songwhipApi/users/types';
import type { FC } from 'react';

const getRUMConfig = () => {
  const env =
    process.env.NEXT_PUBLIC_DATADOG_RUM_ENV ||
    process.env.NEXT_PUBLIC_SONGWHIP_ENV ||
    'development';

  const applicationId =
    process.env.NEXT_PUBLIC_DATADOG_RUM_APPLICATION_ID || '';

  const clientToken = process.env.NEXT_PUBLIC_DATADOG_RUM_CLIENT_TOKEN || '';

  return { applicationId, clientToken, env };
};

interface Props {
  isLoggedIn: boolean;
  user?: MappedUser;
}

/**
 * Datadog RUM (Real User Monitoring) component
 * Implements Datadog RUM using CDN async approach
 */
export const DatadogRUM: FC<Props> = ({ isLoggedIn, user }) => {
  const { applicationId, clientToken, env } = getRUMConfig();

  // Handle clean up when component unmounts or login state changes
  useEffect(() => {
    return () => {
      if (!isLoggedIn && typeof window !== 'undefined' && 'DD_RUM' in window) {
        // @ts-expect-error - DD_RUM is added to window by script
        window.DD_RUM.stopSession();
      }
    };
  }, [isLoggedIn]);

  useEffect(() => {
    if (
      user !== undefined &&
      typeof window !== 'undefined' &&
      'DD_RUM' in window
    ) {
      // @ts-expect-error - DD_RUM is added to window by script
      window.DD_RUM.onReady(() => {
        // @ts-expect-error - DD_RUM is added to window by script
        window.DD_RUM.setUser({
          id: user.id,
          name: user.name,
          email: user.email,
          isEmployee: user.isEmployee,
        });
      });
    }
  }, [user]);

  // Don't render if required props are missing or the user is not logged in
  if (!applicationId || !clientToken || !env || !isLoggedIn) {
    return null;
  }

  return (
    <Script id="datadog-rum" strategy="afterInteractive">
      {`
        (function(h,o,u,n,d) {
          h=h[d]=h[d]||{q:[],onReady:function(c){h.q.push(c)}}
          d=o.createElement(u);d.async=1;d.src=n
          n=o.getElementsByTagName(u)[0];n.parentNode.insertBefore(d,n)
        })(window,document,'script','https://www.datadoghq-browser-agent.com/us1/v6/datadog-rum.js','DD_RUM')
        window.DD_RUM.onReady(function() {
          try {
            window.DD_RUM.init({
              clientToken: '${clientToken}',
              applicationId: '${applicationId}',
              site: 'datadoghq.com',
              service: 'songwhip',
              env: '${env}',
              sessionSampleRate: 100,
              sessionReplaySampleRate: 20,
              defaultPrivacyLevel: 'mask-user-input',
            });
          } catch (error) {
            console.error('Failed to initialize Datadog RUM:', error);
          }
        })
      `}
    </Script>
  );
};
