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

const Closure: React.FC<RingProps> = ({ ring, user }) => {
  const {
    closure: { video },
  } = ring;

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

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

  const onFinish = async (): Promise<void> => {
    const response = await updatePhaseAndScore(user, 4, ring.id);
    setShowEnd(true);
    setScore(response.data.team.totalScore);
  };
  return (
    <>
      {showEndOfPhase && (
        <EndOfPhase
          ring={ring}
          phase={Phases.Four}
          points={0}
          teamMembers={user.team?.members}
          totalScore={score}
        />
      )}
      <section className="closure">
        <PhaseHeader ring={ring} icon={<ClosureIcon />} phase="Cierre" 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={video}
            frameBorder="0"
            allow="accelerometer; encrypted-media; gyroscope; picture-in-picture"
            allowFullScreen
            title="Video Cierre"
          />
        </article>
      </section>
    </>
  );
};

export default Closure;
