/* eslint-disable no-nested-ternary */
import React from 'react';
import PropTypes from 'prop-types';
import { commaSeperate, formatDate } from '../../../../gatsby-core-theme/helpers/lotto';
import { formatScore, formatLowerCase } from '../../../../gatsby-core-theme/helpers/sportstake';
import styles from './table.module.scss';

const Table = ({
  headerList,
  rowList,
  isResult = false,
  isDivTable = false,
  resultTableNumber = 0,
}) => {
  const getIcon = (result) => {
    switch (result?.toLowerCase()) {
      case 'home':
      case 'home win':
        return (
          <div className={styles.home}>
            <div className={styles.circle}>
              <span>1</span>
            </div>
            <span>HOME WIN</span>
          </div>
        );
      case 'away':
      case 'away win':
        return (
          <div className={styles.away}>
            <div className={styles.circle}>
              <span>2</span>
            </div>
            <span>AWAY WIN</span>
          </div>
        );
      case 'draw':
        return (
          <div className={styles.draw}>
            <div className={styles.circle}>
              <span>X</span>
            </div>
            <span>DRAW</span>
          </div>
        );
      case 'postponed':
        return (
          <div className={styles.cancelled}>
            <span>POSTPONED</span>
          </div>
        );
      case 'cancel':
      case 'cancelled':
        return (
          <div className={styles.cancelled}>
            <span>CANCELLED</span>
          </div>
        );
      default:
        return null;
    }
  };

  const getMobileRows = (game, index, matchNr) => {
    const hasIcon = !!getIcon(game?.results);

    return isDivTable ? (
      <>
        <td className={`${styles.mobileOnly} ${index === 0 && styles.firstCard}`}>
          <span>
            Div {index + 1} {game?.number} Match {matchNr - index} out of 13 Fixtures
          </span>
        </td>
        <td className={`${styles.mobileOnly} ${index === 0 && styles.firstCard}`}>
          <div className={styles.cardBox}>
            <div>
              <span>Number of Winners:</span> <span>{game?.winners || game?.no_of_winners}</span>
            </div>
            <div>
              <span>Payout per Winner:</span>{' '}
              <span>{`R${commaSeperate(
                parseFloat(game?.payout) || parseFloat(game?.payout_per_winner_system)
              )} `}</span>
            </div>
          </div>
        </td>
      </>
    ) : (
      <>
        <td className={`${styles.mobileOnly} ${index === 0 && styles.firstCard}`}>
          {hasIcon && <span>{index + 1}.</span>}
          <span>{`${formatLowerCase(game?.homeTeam)}vs ${formatLowerCase(game?.awayTeam)}`}</span>
        </td>
        <td className={`${styles.mobileOnly} ${index === 0 && styles.firstCard}`}>
          {game?.toss && (
            <div>
              <span>Toss:</span> <span>{getIcon(game?.toss)}</span>
            </div>
          )}
          <div>
            <span>Date:</span> <span>{formatDate(game?.dateTime, 'dd/mmm/yy')}</span>
          </div>
          {hasIcon && (
            <>
              <div>
                <span>Score:</span> <span>{formatScore(game?.score)}</span>
              </div>
              <div>{getIcon(game?.results)}</div>
            </>
          )}
        </td>
      </>
    );
  };

  const getTableDataValue = (game, key) => {
    switch (key) {
      case 'toss':
      case 'results':
        return isResult ? (
          <td className={`${!isResult && styles.hideDesktopRow}`}>{getIcon(game[key])}</td>
        ) : null;
      case 'score':
        return (
          <td className={`${!isResult && styles.hideDesktopRow}`}>
            <span>{formatScore(game[key])}</span>
          </td>
        );
      case 'payout_per_winner_system':
      case 'payout': {
        return (
          <td>
            <span>{`R${commaSeperate(parseFloat(game[key]))} `}</span>
          </td>
        );
      }
      case 'dateTime':
        return (
          <td>
            <span>{`${formatDate(game[key], 'dd/mmm/yy')}`}</span>
          </td>
        );
      case 'no_of_winners':
      case 'winners':
        return (
          <td>
            <span>{game[key]}</span>
          </td>
        );
      case 'homeTeam':
      case 'awayTeam':
        return (
          <td className={styles[key]}>
            <span>{game[key]}</span>
          </td>
        );
      default:
        return null;
    }
  };

  const getKeys = (game) => {
    const arrKey = [
      'homeTeam',
      'awayTeam',
      'toss',
      'dateTime',
      'score',
      'results',
      'winners',
      'payout',
      'no_of_winners',
      'payout_per_winner_system',
    ];
    return arrKey
      .map((key) => (game[key] ? key : game[key] === 0 || '' ? key : null))
      .filter((elm) => elm);
  };

  const getRows = () => (
    <>
      {rowList.map((game, index) => {
        const keys = getKeys(game);
        const matchNr = resultTableNumber;
        const num = matchNr;

        return (
          <tr>
            {keys.length ? (
              <td>
                <span>{isDivTable ? `Div ${index + 1}` : index + 1} </span>
              </td>
            ) : null}
            {isDivTable && (
              <td>
                <span>{`Match ${num - index} out of ${matchNr} Fixtures`}</span>
              </td>
            )}
            {keys.map((key) => getTableDataValue(game, key))}
            {getMobileRows(game, index, matchNr)}
          </tr>
        );
      })}
    </>
  );

  return (
    <div className={styles.tableWrapper}>
      <table className={styles.table}>
        <thead>
          <tr>
            {headerList.map((title) => (
              <th>
                <span>{title}</span>
              </th>
            ))}
          </tr>
        </thead>
        <tbody>{getRows()}</tbody>
      </table>
    </div>
  );
};

export default Table;

Table.propTypes = {
  headerList: PropTypes.shape([]),
  rowList: PropTypes.arrayOf(PropTypes.shape({})),
  isResult: PropTypes.bool,
  isDivTable: PropTypes.bool,
  resultTableNumber: PropTypes.number,
};
