import React, { useRef, useState } from 'react';
import { Phases } from '../../../model/common';
import { RingProps } from '../../../model/components/ring';
import updatePhaseAndScore from '../../../utils/updatePhaseAndScore';
import RoundedButton from '../../common/RoundedButton';
import ClinicCaseIcon from '../../icons/ClinicCase';
import upload from '../../upload';
import EndOfPhase from './EndOfPhase';
import PhaseHeader from './PhaseHeader';

const ClinicCase: React.FC<RingProps> = ({ ring, user }) => {
  const {
    clinicCase: {
      template: { url },
      picture,
    },
  } = ring;

  const {
    formats: { thumbnail, small, medium },
  } = picture;
  const ref = useRef<HTMLInputElement>(null);
  const [file, setFile] = useState<File>();
  const [showEndOfPhase, setShowEnd] = useState<boolean>(false);

  const onInputChange = (e: React.ChangeEvent<HTMLInputElement>): void => {
    const { files } = e.currentTarget;

    if (files) {
      const uploaded = files[0];
      setFile(uploaded);
    }
  };

  const onSubmit = async (): Promise<void> => {
    const formData = new FormData();
    formData.append('team', user.team.id);
    formData.append('file', file);

    const response = await upload(file);

    if (response.ok) {
      await updatePhaseAndScore(
        user,
        3,
        ring.id,
        undefined,
        undefined,
        response.data,
      );
    }
    setShowEnd(true);
  };

  return (
    <>
      {showEndOfPhase && (
        <EndOfPhase
          ring={ring}
          phase={Phases.Clinic}
          points={0}
          teamMembers={user.team?.members}
          totalScore={user.team.totalScore}
        />
      )}
      <section className="challenge clinicCase">
        <PhaseHeader
          ring={ring}
          icon={<ClinicCaseIcon />}
          phase="Práctica Clínica"
        />
        <form method="get" action={url}>
          <fieldset>
            <div className="questionsWrapper">
              <div className="questionsPosition">
                <div className="questionItem">
                  <div className="questionItemWrapper">
                    <div className="content left">
                      <div className="contentWrapper">
                        <h2>Comparte tu caso clínico grupal</h2>
                        <p className="points">
                          1<span>pto</span>
                        </p>
                      </div>
                      <div className="imageWrapper">
                        {/* TODO: Imagen caso clínico */}
                        <img
                          alt="Imagen caso clínico"
                          src={medium?.url || small?.url || thumbnail?.url}
                        />
                      </div>
                    </div>
                    <div className="content right">
                      <p>
                        Descárgate la plantilla en Power Point del caso clínico,
                        rellénala junto con tu equipo y súbela de nuevo para que
                        sea evaluada por el comité dialípico.
                      </p>
                      <div className="actions">
                        <RoundedButton
                          title="Descargar plantilla"
                          type="submit"
                        />
                        <RoundedButton
                          title="Subir caso clínico"
                          className="grey"
                          onClick={(): void => {
                            ref.current.click();
                          }}
                        />
                        <input
                          style={{ display: 'none' }}
                          type="file"
                          ref={ref}
                          onChange={onInputChange}
                        />
                        {file ? <p>{file.name}</p> : undefined}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div className="controls">
              <RoundedButton
                type="button"
                title="Completar"
                size="small"
                onClick={onSubmit}
              />
            </div>
          </fieldset>
        </form>
      </section>
    </>
  );
};

export default ClinicCase;
