import React, { useRef, useState } from "react";
import { Button, TextField, Typography } from "@material-ui/core";
import { DropzoneArea } from "material-ui-dropzone";
import { useUserContext } from "../../Contexts/UserContext";
import { useStatusContext } from "../../Contexts/StatusContext";
import {
  useFileUploadContext,
  FileUploadProvider,
} from "../../Contexts/FileUploadContext";
import ModalProgressBar from "../../ModalProgressBar";
import useStyles from "../../useStyles";
import { Redirect } from "react-router";

const FileUploadZone = ({ classes, token }) => {
  const { setFiles } = useFileUploadContext();
  const { setMessage } = useStatusContext();

  return (
    <>
      <DropzoneArea
        id="dropzone"
        showPreviews={true}
        showPreviewsInDropzone={false}
        useChipsForPreview
        previewGridProps={{ container: { spacing: 1, direction: "row" } }}
        previewChipProps={{ classes: { root: classes.previewChip } }}
        previewText="Selected files"
        maxFileSize={1e9}
        filesLimit={1}
        showAlerts={false}
        onChange={(files) => setFiles(files)}
        onDelete={(files) => setFiles(files)}
        onDropRejected={(files) => {
          setMessage(`Rejected ${files[0].name} too large`);
        }}
      />
      <ModalProgressBar />
    </>
  );
};

const MainForm = () => {
  const { uploading, upload, files, cancel } = useFileUploadContext();
  const { token } = useUserContext();
  const { setMessage } = useStatusContext();
  const [redirect, setRedirect] = useState(null);
  const classes = useStyles();
  const packagenameEl = useRef(null);
  const versionEl = useRef(null);
  const descEl = useRef(null);
  const releasenotesEl = useRef(null);
  const onSubmit = async (event) => {
    try {
      event.preventDefault();
      const {
        idToken: { jwtToken: authToken },
      } = token;
      const formData = {
        packagename: packagenameEl.current.value,
        version: versionEl.current.value,
        description: descEl.current.value,
        releasenotes: releasenotesEl.current.value,
      };
      const result = await upload(formData, authToken, files);

      if (!result || result.error) return;

      cancel();
      setMessage(`Package uploaded`);
      setRedirect(`/carupdate-deploy/${result.id}`);
    } catch (e) {
      setMessage(e.message);
    }
  };

  if (redirect && redirect.length > 0) {
    return <Redirect to={redirect} />;
  }

  return (
    <div className={classes.paper}>
      <Typography component="h1" variant="h5">
        Create Update Package
      </Typography>
      <form className={classes.form} noValidate action="{onSubmit}">
        <TextField
          id="packagename"
          name="packagename"
          label="Package name"
          variant="outlined"
          margin="normal"
          inputProps={{
            maxLength: "255",
          }}
          required
          fullWidth
          inputRef={packagenameEl}
        />
        <TextField
          id="version"
          name="version"
          label="Version"
          variant="outlined"
          margin="normal"
          inputProps={{
            maxLength: "255",
          }}
          required
          fullWidth
          inputRef={versionEl}
        />
        <TextField
          id="description"
          name="description"
          label="Description"
          variant="outlined"
          margin="normal"
          inputProps={{
            maxLength: "5120",
          }}
          required
          fullWidth
          multiline
          rows={4}
          placeholder="Package description"
          inputRef={descEl}
        />
        <TextField
          id="releasenotes"
          name="releasenotes"
          label="Release Notes URL"
          variant="outlined"
          margin="normal"
          inputProps={{
            maxLength: "1024",
          }}
          required
          fullWidth
          placeholder="Release Notes URL"
          inputRef={releasenotesEl}
        />
        <FileUploadZone classes={classes} />
        <Button
          type="submit"
          disabled={uploading}
          fullWidth
          variant="contained"
          color="primary"
          className={classes.submit}
          onClick={onSubmit}
        >
          {uploading ? "Uploading..." : "Submit"}
        </Button>
      </form>
    </div>
  );
};

export default function FileUploadForm() {
  return (
    <FileUploadProvider>
      <MainForm />
    </FileUploadProvider>
  );
}
