import React, { useContext, useState } from 'react';
import Loader from '@components/common/Loader';
import { getPlateRecognized } from '@actions/CaptureActions';
import Button from '@components/common/Button';
import RootContext from '@context/RootContext';
import RecognitionResults from '@components/alpr/RecognitionResults';

const UploadCapture = ({ imgSrc, onBackClick }) => {
  const [hasFetched, setHasFetched] = useState(false);
  const { state: { alpr: { isFetchingALPR } }, dispatch } = useContext(RootContext);
  const onUploadClick = () => {
    getPlateRecognized(imgSrc)(dispatch);
    setHasFetched(true);
  };
  return (
    <div className="container">
      {isFetchingALPR ? <Loader /> : (
        <div className="row">
          <img src={imgSrc} alt="captured" />
        </div>
      )}
      {hasFetched && !isFetchingALPR && (<RecognitionResults />)}
      <div className="row button-container">
        <Button text="Back" onClick={onBackClick} />
        {!hasFetched && <Button text="Upload" onClick={onUploadClick} />}
      </div>
    </div>
  );
};

const Capture = ({
  imgSrc, isCapturing, error, onBackClick,
}) => (
  <div className="capture-container row">
    {isCapturing && (<Loader />)}
    {error ? (<p>{error}</p>) : (<UploadCapture imgSrc={imgSrc} onBackClick={onBackClick} />)}
  </div>
);

export default Capture;
