/* eslint-disable import/no-extraneous-dependencies */
/* eslint-disable camelcase */
import React, { useContext } from 'react';
import PropTypes from 'prop-types';
import { Context } from 'gatsby-core-theme/src/context/MainProvider';
import { translate, getBonus } from 'gatsby-core-theme/src/helpers/getters';
import Link from 'gatsby-core-theme/src/hooks/link';
import PrettyLink from '~atoms/pretty-link';

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

const CasinosTable = ({ module, page }) => {
  const { translations } = useContext(Context);
  const { items } = module || {};

  const oneLiner = ({ one_liner }) => {
    if (one_liner) {
      const [firstLine, secondLine] = one_liner.split('+');
      return (
        <>
          <span className={styles?.firstLine || ''}>
            {firstLine}
            <br />
          </span>
          {secondLine && <span className={styles?.secondLine || ''}>{`+${secondLine}`}</span>}
        </>
      );
    }
    return <></>;
  };

  return (
    <div className={styles?.container || ''}>
      <table>
        <thead>
          <tr>
            <th>{`${translate(translations, 'online_casino', 'Online casino')}`}</th>
            <th>{`${translate(translations, 'welcome_bonus', 'Welcome bonus')}`}</th>
            <th>{`${translate(translations, 'visit_online_casino', 'Visit online casino')}`}</th>
          </tr>
        </thead>
        <tbody>
          {items &&
            items.map((item) => (
              <tr>
                <td>
                  <Link
                    to={item.path || item.relation.path}
                    title={item.title}
                    className={`${styles?.casinoLogo || ''} table-operator-card-gtm`}
                  >
                    {item.relation.bonus?.operator_name || item.relation.name}
                  </Link>
                </td>
                <td>
                  {getBonus('main', item?.relation) && oneLiner(getBonus('main', item?.relation))}
                </td>
                <td style={{ textAlign: 'left' }}>
                  <PrettyLink
                    operator={item.relation}
                    pageTemplate={page?.template}
                    module="operator_table"
                    tracker="main"
                    clickedElement="operator_table_cta"
                    className="table-operator-card-gtm btn-cta"
                  >
                    {`${translate(translations, 'visit_table', 'Visit')} ${item?.relation?.name}`}
                  </PrettyLink>
                </td>
              </tr>
            ))}
        </tbody>
      </table>
    </div>
  );
};

export default CasinosTable;

CasinosTable.propTypes = {
  module: PropTypes.shape({
    items: PropTypes.arrayOf({}),
  }).isRequired,
  page: PropTypes.shape({
    template: PropTypes.string,
  }),
};
