/* eslint-disable no-nested-ternary */
import React, { useContext } from 'react';
import PropTypes from 'prop-types';
import Link from '~hooks/link';
import { imagePrettyUrl } from '~helpers/getters';
import { NavigationContext } from '~organisms/navigation/navigationContext';

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

export default function Item({ item, gtmClass = '' }) {
  const { setShowMenu } = useContext(NavigationContext);

  const handleClose = () => {
    setShowMenu(false);
  };

  const ItemImage = () =>
    item.image ? (
      <img width="32" height="32" src={imagePrettyUrl(item.image, 32, 32)} alt={item.title} />
    ) : null;

  return (
    <>
      {item.value?.includes('http') || item.value?.includes('www') ? (
        <a
          aria-label={`${item?.title} link`}
          href={item.value ? item.value : '#'}
          title={item.title}
          rel={`noreferrer ${item.nofollow && 'nofollow'}`}
          target="_blank"
          className={`${styles.item || ''} ${gtmClass || ''}`}
          onClick={() => handleClose()}
        >
          <ItemImage />
          {item.title}
        </a>
      ) : item.value !== null ? (
        <Link
          disabled={item.value === null}
          to={item.value}
          title={item.title}
          rel={item.nofollow && 'nofollow'}
          aria-label={`${item?.title} link`}
          className={`${styles.item || ''} ${gtmClass || ''}`}
          onClick={() => handleClose()}
        >
          <ItemImage />
          {item.title}
        </Link>
      ) : (
        <span className={`${styles.item || ''} ${gtmClass || ''} ${styles.inactiveLink}`}>
          {item.title}
        </span>
      )}
    </>
  );
}

Item.propTypes = {
  item: PropTypes.shape({
    title: PropTypes.string,
    value: PropTypes.string,
    nofollow: PropTypes.bool,
    image: PropTypes.string,
  }).isRequired,
  gtmClass: PropTypes.string,
};
