/* eslint-disable no-nested-ternary */
/* eslint-disable no-underscore-dangle */
import React from 'react';
import PropTypes from 'prop-types';
import { getApiQueryParams } from '../../../../gatsby-core-theme/helpers/sportstake';
import { formatDate } from '../../../../gatsby-core-theme/helpers/lotto';
import { tableHeader } from '../../../../gatsby-core-theme/constants/sportstake';
import Table from '../table';
import styles from './fixtures.module.scss';

const Fixtures = ({ module, serverData }) => {
  if (!serverData) {
    return;
  }

  const { name: moduleName } = module;
  const isCricket = moduleName.includes('cricket');
  const isSportstake4 = moduleName.includes('sportstake4');
  const hasTwoTables = moduleName.includes('sportstake8') || isSportstake4;
  const query = getApiQueryParams(moduleName);

  const { games } = serverData?.drawDetails || {};

  const firstTableGames = games
    ? hasTwoTables || isCricket
      ? Object.values(games).slice(...query.firstTable)
      : Object.values(games)
    : [];

  const secondTableGames = games ? Object.values(games).slice(...query.secondTable) : [];

  const headerList = tableHeader.slice(0, 4);

  const SportstakeHeader = () => {
    const nrOfFixtures = serverData?._id?.split('-')[1];
    const formattedDate = formatDate(serverData?.drawDate, 'dd/MMM/yy');
    return (
      <div className={styles.sportstakeHeader}>
        <p>{`Fixtures List for ${nrOfFixtures} (Provisional) ${formattedDate}`} </p>
      </div>
    );
  };

  return (
    <div className={`${styles.sportstake} ${hasTwoTables && styles.twoHalfs}`}>
      <SportstakeHeader />
      {isSportstake4 && <h3>1st half</h3>}
      <Table headerList={headerList} rowList={firstTableGames} />
      {hasTwoTables && (
        <>
          <h3>{!isSportstake4 ? '2nd Half' : 'Full Time'}</h3>
          <Table headerList={headerList} rowList={secondTableGames} />
        </>
      )}
    </div>
  );
};

export default Fixtures;

Fixtures.propTypes = {
  page: PropTypes.shape({}),
  module: PropTypes.shape({
    items: PropTypes.arrayOf(PropTypes.shape({})),
    style: PropTypes.string,
    name: PropTypes.string,
    module_title: PropTypes.string,
    module_introduction: PropTypes.string,
  }).isRequired,
  pageContext: PropTypes.shape({}),
  serverData: PropTypes.shape({
    _id: PropTypes.string,
    drawDate: PropTypes.string,
    drawDetails: PropTypes.shape({
      games: PropTypes.shape({}),
      divs: PropTypes.shape({}),
    }),
  }),
};
