/* eslint-disable no-shadow */
/* eslint-disable camelcase */
/* eslint-disable react/prop-types */
import React from 'react';
import LazyImage from '~hooks/lazy-image';
import styles from './event.module.scss';
import Score from '../../../../atoms/score';
import EventDetails from '../../../../organisms/odds';

export const TeamDefImg = ({ alt = '' }) => (
  <img alt={alt} src="../../../../../images/default.svg" width={136} height={136} />
);

export default function Index({ page, serverData }) {
  const team = (team) => (
    <div className={styles.team}>
      <LazyImage
        src={`https://di0up76ym3ymc.cloudfront.net/logos/team/${team.participant.id}.png`}
        alt={team.name}
        width={136}
        height={136}
        loading="eager"
        defaultImg={<TeamDefImg alt={team.name} />}
      />
      <p>{team.participant.name}</p>
    </div>
  );

  const getFinalResult = (results) => {
    let finalResult = null;

    results.forEach((res) => {
      if (res.code === 'finalresult' || res.code === 'runningscore') {
        finalResult = res.value;
      }
    });

    return finalResult;
  };

  if (!serverData?.details) {
    return <h1>Loading</h1>;
  }

  const {
    competitors: [homeTeam, awayTeam],
    start_date,
    status,
  } = serverData.details;
  const homeTeamGoal = getFinalResult([...homeTeam.results]);
  const awayTeamGoal = getFinalResult([...awayTeam.results]);

  const operatorList =
    page.sections.header &&
    page.sections.header.modules &&
    page.sections.header.modules.length > 0 &&
    page.sections.header.modules[0].name === 'top_list'
      ? page.sections.header.modules[0].items[0].items
      : [];

  return (
    <div className={styles.container}>
      <div className={styles.eventDetails}>
        {team(homeTeam)}
        <Score
          start_date={start_date}
          homeTeamGoal={homeTeamGoal}
          status={status.name}
          awayTeamGoal={awayTeamGoal}
        />
        {team(awayTeam)}
      </div>

      <EventDetails
        operatorList={operatorList}
        oddsData={serverData.odds}
        eventDetails={serverData.details}
      />
    </div>
  );
}
