/* eslint-disable no-shadow */
/* eslint-disable react/prop-types */
import React from 'react';
import { sortSquadByCategories, groupBy } from 'sports-util';
import styles from './lineups.module.scss';
import LazyImage from '~hooks/lazy-image';

export default function index({ lineups }) {
  const homeTeam = lineups[0];
  const awayTeam = lineups[1];

  const [homeTeamList, awayTeamList] = sortSquadByCategories(lineups, 'role.name');

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

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

  const getTeamList = (teamList, home) => {
    const lineup = groupBy(teamList.Lineup, 'role.name');
    const lineupOrder = ['Goalkeeper', 'Defence', 'Midfield', 'Forward'];
    return (
      <div>
        {lineupOrder.map(
          (role) =>
            lineup[role] &&
            lineup[role].map((player) => (
              <div className={`${styles.playerRow} ${!home ? styles.reverse : ''}`}>
                <span>{player.shirt_number}</span>
                <span>{player.member.name}</span>
              </div>
            ))
        )}

        {teamList.Substitutes && teamList.Substitutes.length > 0 && (
          <p className={`${styles.label} ${!home ? styles.awaylabel : ''}`}>Substitutes</p>
        )}
        {teamList.Substitutes &&
          teamList.Substitutes.length > 0 &&
          teamList.Substitutes.map((player) => (
            <div className={`${styles.playerRow} ${!home ? styles.reverse : ''}`}>
              <span>{player.shirt_number}</span>
              <span>{player.member.name}</span>
            </div>
          ))}

        {teamList.Manager && teamList.Manager.length > 0 && (
          <p className={`${styles.label} ${!home ? styles.awaylabel : ''}`}>Manager</p>
        )}
        {teamList.Manager &&
          teamList.Manager.map((player) => (
            <div className={`${styles.playerRow} ${!home ? styles.reverse : ''}`}>
              <span>{player.member.name}</span>
            </div>
          ))}
      </div>
    );
  };

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        {team(homeTeam.competitor)}
        {team(awayTeam.competitor)}
      </div>
      <div className={styles.lineupContainer}>
        {getTeamList(homeTeamList, true)}
        {getTeamList(awayTeamList, false)}
      </div>
    </div>
  );
}
