import React, { useState } from "react";
import firebase from "firebase/app";
import "firebase/storage";
import { Stack } from "@mui/system";
import { Button } from "@mui/material";

const IDLE = 0;
const IMAGE_SET = 1;
const UPLOADING = 2;
const DONE = 3;

function ImageUpload({ onImageURLSet }) {
  const [state, setState] = useState();
  const [image, setImage] = useState(null);
  const [imageUrl, setImageUrl] = useState("");
  const [progress, setProgress] = useState(0);

  const handleChange = (e) => {
    if (e.target.files[0]) {
      // setState(1);
      let image = e.target.files[0];

      const uploadTask = firebase
        .storage()
        .ref(`images/${image.name}`)
        .put(image);

      setState(UPLOADING);

      uploadTask.on(
        "state_changed",
        (snapshot) => {
          const progress = Math.round(
            (snapshot.bytesTransferred / snapshot.totalBytes) * 100
          );
          setProgress(progress);
        },
        (error) => {
          console.log(error);
        },
        () => {
          firebase
            .storage()
            .ref("images")
            .child(image.name)
            .getDownloadURL()
            .then((url) => {
              setImageUrl(url);
              setProgress(0);
              setImage(null);
              onImageURLSet(url);
              setState(3);
            });
        }
      );
    }
  };

  let componente;
  switch (state) {
    default:
    case IDLE:
      componente = (
        <>
          <input
            style={{ display: "none" }}
            id="raised-button-file"
            multiple
            type="file"
            accept="image/*"
            capture="camera"
            onChange={handleChange}
          />
          <label htmlFor="raised-button-file">
            <Button style={{ padding: 20, width: "100%" }} component="span">
              Aggiungi un'immagine
            </Button>
          </label>
        </>
      );
      break;
    case IMAGE_SET:
      componente = (
        <Stack
          spacing={2}
          style={{ justifyContent: "center", alignItems: "center" }}
        >
          <img style={{ width: 200 }} src={URL.createObjectURL(image)} />
          <Stack
            spacing={4}
            style={{ width: "100%", justifyContent: "center" }}
            direction="row"
          >
            <Button
              onClick={() => {
                setState(IDLE);
              }}
            >
              riprova
            </Button>
            <Button onClick={handleUpload}>carica</Button>
          </Stack>
        </Stack>
      );
      break;

    case UPLOADING:
      componente = (
        <div style={{ width: "100%" }}>
          <progress style={{ width: "100%" }} value={progress} max="100" />
        </div>
      );
      break;

    case DONE:
      componente = (
        <div>
          <img style={{ width: 200 }} src={imageUrl} />
        </div>
      );
  }

  return componente;
}

export default ImageUpload;
