/* eslint-disable import/no-extraneous-dependencies */
/* eslint-disable no-unused-expressions */
/* eslint-disable prefer-destructuring */
/* eslint-disable react-hooks/exhaustive-deps */
import React, { useRef, useContext } from 'react';
import { translate } from 'gatsby-core-theme/src/helpers/getters';
import PropTypes from 'prop-types';

import ScollX from 'gatsby-core-theme/src/hooks/scroll-x';
import keygen from '~helpers/keygen';
import { anchorLink, removeSymbols } from '~helpers/strings';
import { Context } from '~context/MainProvider';
import styles from './template-two.module.scss';

function Anchor({ module: { items }, icon = null, showTitle = true, exclOperator = false }) {
  const itemsRef = useRef([]);
  const anchorContainerRef = useRef(null);
  const anchorListRef = useRef(null);
  const { translations } = useContext(Context) || {};
  const anchorList = items.map((anchor) => ({
    id: `${anchor.label && removeSymbols(anchorLink(anchor?.label?.toLowerCase().trim()))}`,
    label: anchor.label,
    slug: `${anchor.label && anchorLink(anchor?.label?.toLowerCase().trim())}`,
  }));

  return (
    <div className={styles.containerAnchor || ''} ref={anchorContainerRef}>
      {showTitle ? (
        <div className={`${styles.anchorTitle || ''}`}>
          <span>
            {translate(
              translations,
              'anchor_title_responsible_gambling',
              'You Might Wanna Jump To:)'
            )}
          </span>
        </div>
      ) : null}
      <div
        className={`${styles.defaultConatiner || ''} ${
          exclOperator ? styles.usingExclOperator || '' : ''
        } `}
      >
        <ScollX refTag={anchorListRef}>
          <ul ref={anchorListRef} className={`${styles.anchor || ''}`}>
            {anchorList?.map((item, index) => (
              <li className={styles.anchorItem || ''}>
                <a
                  className={`${styles.link || ''} anchor-carousel-gtm anchor-menu-gtm`}
                  key={keygen()}
                  draggable="false"
                  // eslint-disable-next-line no-return-assign
                  ref={(el) => (itemsRef.current[index] = el)}
                  href={`#${item?.id && item.id}`}
                >
                  {translate(translations, item.slug, item.label)}
                  {icon}
                </a>
              </li>
            ))}
          </ul>
        </ScollX>
      </div>
    </div>
  );
}

Anchor.propTypes = {
  exclOperator: PropTypes.bool,
  module: PropTypes.shape({
    items: PropTypes.arrayOf(
      PropTypes.shape({
        label: PropTypes.string,
      })
    ),
  }).isRequired,
  headerOffset: PropTypes.number.isRequired,
  styles: PropTypes.shape({}),
  icon: PropTypes.element,
  showTitle: PropTypes.string,
};

export default Anchor;
