/* eslint-disable no-unused-expressions */
/* 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, commaSeperate } from '../../../../gatsby-core-theme/helpers/lotto';
import {
  divHeader,
  tableHeader,
  tableHeaderCricket,
  tossResultsHeader,
} from '../../../../gatsby-core-theme/constants/sportstake';
import Table from '../table';
import styles from './results.module.scss';

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

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

  const { games, divs } = serverData?.drawDetails || {};
  const { winnerData } = serverData?.more_info || {};
  const { totalPrizePool, estimatedJackpot, nextEstimatedJackpotAmt } = serverData?.more_info || {};

  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 = isCricket ? tableHeaderCricket : tableHeader;

  const divsList = divs ? Object.values(divs) : winnerData ? Object.values(winnerData) : [];

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

  const DivTable = () => (
    <div className={styles.divTable}>
      <div className={styles.tablesContainer}>
        <Table
          headerList={divHeader}
          rowList={divsList}
          isDivTable
          resultTableNumber={query.secondTableStart}
        />

        {isCricket && (
          <Table
            headerList={tossResultsHeader}
            rowList={serverData?.toss_results?.winnerData}
            isDivTable
            resultTableNumber={query.secondTableStart}
          />
        )}
      </div>
      <div className={styles.jackpotDiv}>
        <p>Total Prize Pool:</p>
        <h3>R{commaSeperate(parseFloat(totalPrizePool))}</h3>
        <p>Next Estimated Jackpot:</p>
        <h3>
          R{commaSeperate(parseFloat(estimatedJackpot) || parseFloat(nextEstimatedJackpotAmt))}
        </h3>
      </div>
    </div>
  );

  const mutateObjectAtributes = (obj) => {
    obj.forEach((element, index) => {
      obj[index] = {
        homeTeam: element.homeTeam,
        awayTeam: element.awayTeam,
        toss: element.toss_winner,
        dateTime: element.eventDate,
        score: isCricket
          ? `${element.homeScore || '0/0'}`
          : `${element.homeScore}-${element.awayScore}`,
        results: element.result,
      };
    });
  };

  newSportStakes && mutateObjectAtributes(firstTableGames);
  newSportStakes && mutateObjectAtributes(secondTableGames);

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

export default Results;

Results.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({}),
    }),
    more_info: PropTypes.shape({}),
    toss_results: PropTypes.shape({
      winnerData: PropTypes.arrayOf(PropTypes.shape({})),
    }),
    winnerData: PropTypes.arrayOf(PropTypes.shape({})),
  }),
};
