import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import IconButton from '../../common/IconButton';
import ArrowBottom from '../../icons/ArrowBottom';
import Coin from '../../common/Coin';
import { User } from '../../../model/user';
import { Ring } from '../../../model/rings';
import { calculateScore, EXTRA_POINTS_VALUE } from '../../../utils/extraPoints';

interface ComponentProps {
  user: User;
}

const Points: React.FC<ComponentProps> = ({ user }) => {
  const { t } = useTranslation();
  const [isOpen, setOpen] = useState<boolean>(false);
  const { score, totalScore, extraPoints } = user.team;

  return (
    <article className={`pointsMenu ${isOpen ? 'open' : ''}`}>
      <button
        type="button"
        title="Puntuación"
        onClick={(): void => setOpen(!isOpen)}
        className="openButton"
      >
        <div className="title">
          <Coin size="large" />
          <h3>Puntuación</h3>
        </div>
        <h4>
          {calculateScore(totalScore, extraPoints).toFixed(2).replace('.', ',')}
          <span>pts</span>
        </h4>
      </button>
      <IconButton
        title="Cerrar puntuaciones"
        className="closeButton"
        onClick={(): void => setOpen(false)}
      >
        <ArrowBottom />
      </IconButton>
      <span className="divider" />
      <ul className="pointsList">
        {extraPoints && (
          <li className="listItem" key="extraPoints">
            <div className="pointsWrapper">
              <Coin size="medium" />
              <p>{`${EXTRA_POINTS_VALUE.toFixed(2).replace('.', ',')} ptos`}</p>
            </div>
            <p className="pointsOwner">{t('EXTRA_POINTS')}</p>
          </li>
        )}
        {score.map((item) => {
          const scoreUser = item.user as User;
          const userName =
            user._id === scoreUser._id ? 'Tú' : scoreUser.username;
          return (
            <li className="listItem" key={item.id}>
              <div className="pointsWrapper">
                <Coin size="medium" />
                <p>{`${item.points.toFixed(2).replace('.', ',')} pto${
                  item.points !== 1 ? 's' : ''
                }`}</p>
              </div>
              <p className="pointsOwner">{`${item.concept} Anillo ${
                (item.ring as Ring).order
              } - ${userName}`}</p>
            </li>
          );
        })}
      </ul>
    </article>
  );
};

export default Points;
