import React, { FunctionComponent, useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import axios from 'axios';
import style from '../web.module.scss';

import { IPlayerInfo } from '../models/IPlayerInfo';

type ComponentProps = {
};

export const Players: FunctionComponent<ComponentProps> = (props): JSX.Element => {
  const { t } = useTranslation();
  const [playerInfo, setPlayerInfo] = useState<IPlayerInfo[]>([]);
  // @ts-ignore
  const { tournament_key } = useParams();
  useEffect(() => {
    if (playerInfo.length === 0) {
      const url = process.env.REACT_APP_API_URL;
      let apiUrl = `${url}api/players`;
      if (tournament_key) {
        apiUrl += `/${tournament_key}`;
      }
      axios.get(apiUrl)
      .then((response) => {
        if (response.data) {
          setPlayerInfo(response.data);
        }
      });
    }
  }, [tournament_key, playerInfo, setPlayerInfo]);
  const renderPlayerInfo = (): JSX.Element[] => {
    const result: JSX.Element[] = [];
    if (playerInfo.length > 0) {
      playerInfo.forEach((el: IPlayerInfo) => {
        result.push(
          <div
            key={`playerInfoLoop-${el.id}`}
            className={style.characterBlock}
            style={{
              animationDelay:`${el.id*0.2}s`
            }}
          >
            <div className={style[`character-${el.name_id}`]} />
            <div className={style.titlePlayer}><span className={style.titlePlayerBlock}>{t('player_name')}</span></div>
            <div>{el.player_name}</div>
            <div className={style.titlePlayer}><span className={style.titlePlayerBlock}>{t('use_character')}</span></div>
            <div>{el.name_jp}</div>
            <div className={style.titlePlayer}><span className={style.titlePlayerBlock}>{t('description')}</span></div>
            <div>{el.description}</div>
          </div>
        );
      });
    }
    return result;
  };
  return (
    <div className={style.guideBody}>
      <h2>Players</h2>
      <hr />
      <br />
      {renderPlayerInfo()}
    </div>
  );
};
