import React, { useEffect } from 'react';
import PropTypes from 'prop-types';
import LazyImage from '~hooks/lazy-image';
import { imagePrettyUrl, getAltText } from '~helpers/getters';
import { generateTrackerLink } from '~helpers/generators';
import styles from './tracker.module.scss';

export default function TrackerGeo({
  pageContext,
  path,
  mainText = 'One sec, while we load [operator_name] for you..',
  redirectText = 'If the casino has not loaded within a few seconds',
  btnText = 'Click Here!',
  bgImage = '',
  bgVideo = '',
  redirectTimer = 5000,
  logo = '../../../../../images/logo.svg',
  counter = false,
  operatorLogo = false,
  operatorLogoWidth = '80',
  operatorLogoHeight = '80',
}) {
  const { page, operatorsByMarket } = pageContext;
  const operator = operatorsByMarket[Object.keys(operatorsByMarket)[0]][0];
  // eslint-disable-next-line dot-notation
  const defaultMarketOperator = operatorsByMarket[`us_en`] || null;
  const showSplashScreen = typeof window !== 'undefined';

  // eslint-disable-next-line no-shadow
  const getTracker = (operator) => {
    let tracker = '';
    const trackerLinks = operator ? Object.keys(operator.links) : [];
    for (let i = 0; i < trackerLinks.length; i += 1) {
      const trackerLink = trackerLinks[i].toLowerCase().replace(' ', '_');
      if (generateTrackerLink(operator, trackerLink, false, page.template) === path) {
        tracker =
          operator.links[
            Object.keys(operator.links).find(
              (key) => key.toLowerCase() === trackerLink.toLowerCase()
            )
          ];
        break;
      }

      tracker = operator.links.main;
    }
    return tracker;
  };

  const getData = async () => {
    await fetch('https://geolocation-db.com/json/', {
      method: 'GET',
    })
      .then((response) => response.json())
      .then(async (data) => {
        const ipAddress = data.IPv4;
        const apiUrl = `https://pro.ip-api.com/json/${ipAddress}?key=sQhiSjgnSScSHqR&fields=status,countryCode,region,city,zip,lat,lon`;

        await fetch(apiUrl, {})
          .then((response) => response.json())
          .then((data) => {
            if (data.countryCode) {
              const userMarketOperator =
                operatorsByMarket[`us_en_${data.region.toLowerCase()}`] || null;

              const trackerRedirect =
                (userMarketOperator && userMarketOperator[0]) || defaultMarketOperator[0];

              if (trackerRedirect) {
                setTimeout(
                  () => window.location.replace(getTracker(trackerRedirect)),
                  redirectTimer
                );
              } else {
                console.log('No Valid Tracker');
              }
            }
          })
          .catch((err) => {
            console.log(`Error ${err}`);
            setTimeout(
              () => window.location.replace(getTracker(defaultMarketOperator[0])),
              redirectTimer
            );
          });
      })
      .catch((err) => {
        console.log(`Error ${err}`);
        setTimeout(
          () => window.location.replace(getTracker(defaultMarketOperator[0])),
          redirectTimer
        );
      });
  };

  useEffect(() => {
    window.loadGTM = false;
    getData();
  }, []);

  let background = <></>;
  if (bgVideo) {
    background = (
      <video muted autoPlay loop className={styles.background} poster={bgImage && bgImage}>
        <source src={bgVideo} type="video/webm" />
      </video>
    );
  } else if (bgImage) {
    background = <LazyImage className={styles.background} src={bgImage} alt="background image" />;
  }

  const imageObject = operator?.standardised_logo_url_object || operator?.logo_url_object;

  return (
    <>
      {showSplashScreen && (
        <>
          <div className={styles.container}>
            {background}
            <div className={styles.content}>
              <LazyImage alt="Site logo" src={logo} />
              <p
                className={`${styles.mainText} ${operatorLogo && styles.mainTextWithlogo}`}
              >{`${mainText.replace(
                '[operator_name]',
                operator?.bonus?.operator_name || operator.name
              )}`}</p>
              {operatorLogo && (
                <LazyImage
                  src={imagePrettyUrl(
                    imageObject?.filename || operator?.logo_url,
                    operatorLogoWidth,
                    operatorLogoHeight
                  )}
                  alt={getAltText(imageObject, operator.name)}
                  loading="eager"
                  width={operatorLogoWidth}
                  height={operatorLogoHeight}
                  className={styles.operatorlogo}
                />
              )}
              <div className={styles.bar} />
              {counter ? (
                redirectText
              ) : (
                <div
                  className={styles.redirectText}
                  // eslint-disable-next-line react/no-danger
                  dangerouslySetInnerHTML={{ __html: redirectText }}
                />
              )}
            </div>
          </div>
        </>
      )}
    </>
  );
}

TrackerGeo.propTypes = {
  redirectText: PropTypes.oneOfType([PropTypes.string, PropTypes.element]),
  mainText: PropTypes.string,
  btnText: PropTypes.string,
  bgImage: PropTypes.string,
  bgVideo: PropTypes.string,
  path: PropTypes.string,
  logo: PropTypes.string,
  counter: PropTypes.bool,
  redirectTimer: PropTypes.number,
  operatorLogo: PropTypes.bool,
  operatorLogoWidth: PropTypes.string,
  operatorLogoHeight: PropTypes.string,
  pageContext: PropTypes.shape({
    operatorsByMarket: PropTypes.shape({
      bonus: PropTypes.shape({
        operator_name: PropTypes.string,
      }),
      name: PropTypes.string,
      standardised_logo_url_object: PropTypes.shape({}),
      logo_url_object: PropTypes.shape({}),
      logo_url: PropTypes.string,
      links: PropTypes.shape({
        main: PropTypes.string,
        terms_and_conditions: PropTypes.string,
      }),
    }).isRequired,
    page: PropTypes.shape({
      template: PropTypes.string,
    }),
  }),
  styles: PropTypes.shape({}),
};
