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

const SportstakeTable = ({ 
    fixture, 
    query, 
    isCricket = false 
}) => {
    if (!fixture) {return;}
    const { divs } = fixture?.drawDetails || {};
    const { winnerData } = fixture?.more_info || {};
    const { totalPrizePool, estimatedJackpot, nextEstimatedJackpotAmt } = fixture?.more_info || {};

    const normalizeCurrencyValue = (value) => {
      if (value === null || value === undefined || value === '') return null;
      if (typeof value === 'number') return value;
      const parsedValue = parseFloat(String(value).replace(/,/g, '').replace(/[^\d.-]/g, ''));
      return Number.isNaN(parsedValue) ? null : parsedValue;
    };

    const rawDivsList = divs ? Object.values(divs) : winnerData ? Object.values(winnerData) : [];
    const divsList = rawDivsList.map((item) => {
      const normalizedItem = { ...item };
      const payout =
        normalizeCurrencyValue(item?.payout) ??
        normalizeCurrencyValue(item?.payout_per_winner_system) ??
        normalizeCurrencyValue(item?.prizeAmount);

      delete normalizedItem.no_of_winners;
      delete normalizedItem.payout_per_winner_system;

      return {
        ...normalizedItem,
        winners: item?.winners ?? item?.no_of_winners,
        payout,
      };
    });

    const totalPrizePoolValue = normalizeCurrencyValue(totalPrizePool);
    const nextEstimatedJackpotValue =
      normalizeCurrencyValue(estimatedJackpot) ?? normalizeCurrencyValue(nextEstimatedJackpotAmt);

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

            {isCricket && fixture?.toss_results?.winnerData && (
            <Table
                headerList={tossResultsHeader}
                rowList={fixture?.toss_results?.winnerData}
                isDivTable
                resultTableNumber={query.secondTableStart}
            />
            )}
        </div>
        {(totalPrizePoolValue !== null || nextEstimatedJackpotValue !== null) && (
          <div className={styles.jackpotDiv}>
            {totalPrizePoolValue !== null && (
              <>
                <p>Total Prize Pool:</p>
                <h3>R{commaSeperate(totalPrizePoolValue)}</h3>
              </>
            )}
            {nextEstimatedJackpotValue !== null && (
              <>
                <p>Next Estimated Jackpot:</p>
                <h3>R{commaSeperate(nextEstimatedJackpotValue)}</h3>
              </>
            )}
          </div>
        )}
        </div>
    );
}

export default SportstakeTable;

SportstakeTable.propTypes = {
    fixture: 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({})),
    }),
    query: PropTypes.shape({
        secondTableStart: PropTypes.shape({})
    }).isRequired,
    isCricket: PropTypes.bool
  };
  