import React, { useState } from 'react';
import PhaseHeader from './PhaseHeader';
import FormationIcon from '../../icons/Formation';
import { Phases } from '../../../model/common';
import { RingProps } from '../../../model/components/ring';
import RoundedButton from '../../common/RoundedButton';
import RoundedLink from '../../common/RoundedLink';
import EndOfPhase from './EndOfPhase';
import updatePhaseAndScore from '../../../utils/updatePhaseAndScore';

const Formation: React.FC<RingProps> = ({ ring, user }) => {
  const {
    training: {
      url,
      info: { value },
    },
  } = ring;

  const { answers } = user;

  const phase = answers?.find((ans) => ans.ring.id === ring.id)?.phase || 0;

  const showFeedback = phase < 1;
  const [showEndOfPhase, setShowEnd] = useState<boolean>(false);
  const [score, setScore] = useState<number>(0);

  const onFinish = async (): Promise<void> => {
    const result = await updatePhaseAndScore(
      user,
      1,
      ring.id,
      value / user.team.members,
    );
    setScore(result.data.team.totalScore);
    setShowEnd(true);
  };
  return (
    <>
      {showEndOfPhase && (
        <EndOfPhase
          ring={ring}
          phase={Phases.One}
          points={value}
          teamMembers={user.team?.members}
          totalScore={score}
        />
      )}
      <section className="formation">
        <PhaseHeader
          ring={ring}
          icon={<FormationIcon />}
          phase={Phases.One}
          onDark
        />
        <article className="phaseFooter">
          {showFeedback ? (
            <RoundedButton
              title="Finalizar"
              className="white"
              onClick={onFinish}
            />
          ) : (
            <RoundedLink
              title="Salir"
              className="white"
              route={`/ring/${ring.id}`}
            />
          )}
        </article>
        <article className="videoWrapper">
          <iframe
            src={url}
            frameBorder="0"
            allow="accelerometer; encrypted-media; gyroscope; picture-in-picture"
            allowFullScreen
            title="Video Formación"
          />
        </article>
      </section>
    </>
  );
};

export default Formation;
