/* eslint-disable no-nested-ternary */
/* eslint-disable no-underscore-dangle */
import React, { useState, useEffect, useRef } from 'react';
import PropTypes from 'prop-types';
import Tabs from 'gatsby-core-theme/src/hooks/tabs';
import { getApiQueryParams } from '../../../../gatsby-core-theme/helpers/sportstake';
import { getResultsById } from '../../../../gatsby-core-theme/helpers/services';
import { tableHeader } from '../../../../gatsby-core-theme/constants/sportstake';
import SportstakeHeader from './header';
import Table from '../table';

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

const Fixtures = ({ module, serverData }) => {
  const [tabData, setTabData] = useState(null);
  const { name: moduleName } = module;

  const onTabChange = async (tabId) => {
    const response = await getResultsById(serverData?.data[moduleName][tabId.split('_')[1]]._id);
    setTabData(response);
  }

  if (!serverData) {
    return;
  }

  const isCricket = moduleName.includes('cricket');
  const isSportstake4 = moduleName.includes('sportstake4');
  const hasTwoTables = moduleName.includes('sportstake8') || isSportstake4;
  const query = getApiQueryParams(moduleName);

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

  if(!serverData?.data[moduleName]) return;
  const daysOfWeek = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
  const monthsOfYear = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec',];
  const tabs = Object.values(serverData?.data[moduleName]);
  const tabsContainerRef = useRef(null);

  useEffect(() => {
    if (tabsContainerRef.current) {
      tabsContainerRef.current.scrollTop = tabsContainerRef.current.scrollWidth;
    }
  }, []);

  const mutateObjectAtributes = (obj, fallbackDate) => {
    obj.forEach((element, index) => {
      obj[index] = {
        homeTeam: element.homeTeam,
        awayTeam: element.awayTeam,
        toss: element.toss_winner,
        dateTime: element.eventDate || element.dateTime || element.date || fallbackDate,
      };
    });
  };

  return (
    <Tabs
    showAll={false}
    showNumberOfResults
    headerClass="sportstakeTabs"
    activeTabClass='sportstakeTabsActive'
    onTabChange={onTabChange}
    activeIndex={0}
    ref={tabsContainerRef}
    >
    {tabs?.map((res, index) => {
      const activeFixture = tabData || res;
      const { games } = activeFixture?.drawDetails || {};

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

      const secondTableGames = games ? Object.values(games).slice(...query.secondTable) : [];
      mutateObjectAtributes(secondTableGames, activeFixture?.drawDate);
      
      const isLatestTab = (index === 0);
      const drawDate = res?.drawDate ? new Date(res.drawDate) : null;
      const hasValidDrawDate = drawDate && !Number.isNaN(drawDate.getTime());
      const label = isLatestTab
        ? 'Latest'
        : hasValidDrawDate
          ? daysOfWeek[drawDate.getDay()]
          : '';

      const results = hasValidDrawDate
        ? `${monthsOfYear[drawDate.getMonth()]} ${drawDate.getDate()}`
        : '';

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

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.arrayOf(
    PropTypes.shape({
      _id: PropTypes.string,
      data: PropTypes.shape({}),
      drawDate: PropTypes.string,
      drawDetails: PropTypes.shape({
        games: PropTypes.shape({}),
        divs: PropTypes.shape({}),
      }),
    }),
  ) 
};
