import React, { useEffect, useState } from "react";
import { useParams } from "react-router";
import { Button, TextField } from "@material-ui/core";

import {
  UpdatesProvider,
  useUpdatesContext,
} from "../../Contexts/UpdatesContext";
import { useUserContext } from "../../Contexts/UserContext";
import { useStatusContext } from "../../Contexts/StatusContext";
import useStyles from "../../useStyles";
import { tsLocalDateTimeString } from "../../../utils/dates";
import { logger } from "../../../services/monitoring";

const MainForm = () => {
  const { id } = useParams();
  const { getPackages, updatePackage, packages, busy } = useUpdatesContext();
  const {
    token: {
      idToken: { jwtToken: token },
    },
  } = useUserContext();
  const { setMessage, setTitle } = useStatusContext();
  const [packageName, setPackageName] = useState("");
  const [version, setVersion] = useState("");
  const [link, setLink] = useState("");
  const [description, setDescription] = useState("");
  const [releaseNotesLink, setReleaseNotesLink] = useState("");
  const [createDate, setCreateDate] = useState("");
  const classes = useStyles();
  const onSubmit = async (event) => {
    try {
      event.preventDefault();
      const data = {
        id: parseInt(id),
        package_name: packageName,
        version,
        link,
        desc: description,
        release_notes: releaseNotesLink,
      };
      await updatePackage(data, token);
      setMessage(`Updated ${packageName} ${version}`);
    } catch (e) {
      setMessage(e.message);
      logger.warn(e.stack);
    }
  };
  const getData = async () => {
    try {
      getPackages({ id: parseInt(id) }, token);
    } catch (e) {
      setMessage(e.message);
      logger.warn(e.stack);
    }
  };
  const handleChange = (event) => {
    const field = event.target.id;
    const value = event.target.value;

    if (field === "packagename") {
      setPackageName(value);
    } else if (field === "version") {
      setVersion(value);
    } else if (field === "link") {
      setLink(value);
    } else if (field === "description") {
      setDescription(value);
    } else if (field === "releasenotes") {
      setReleaseNotesLink(value);
    }
  };

  useEffect(() => {
    setTitle(`Edit Update Package ${id}`);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    getData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [token]);

  useEffect(() => {
    if (!packages || packages.length === 0) return;
    var data = packages[0];

    setPackageName(data.package_name);
    setVersion(data.version);
    setLink(data.link);
    setDescription(data.desc || "");
    setReleaseNotesLink(data.release_notes || "");
    setCreateDate(tsLocalDateTimeString(data.timestamp));
  }, [packages]);

  return (
    <div className={classes.paper}>
      <form className={classes.form} noValidate action="{onSubmit}">
        <TextField
          label="Create Date"
          variant="filled"
          margin="normal"
          inputProps={{
            readOnly: true,
            maxLength: "1024",
          }}
          value={createDate}
          fullWidth
        />
        <TextField
          id="packagename"
          name="packagename"
          label="Package name"
          variant="outlined"
          margin="normal"
          inputProps={{
            maxLength: "255",
          }}
          value={packageName}
          onChange={handleChange}
          required
          fullWidth
        />
        <TextField
          id="version"
          name="version"
          label="Version"
          variant="outlined"
          margin="normal"
          inputProps={{
            maxLength: "255",
          }}
          value={version}
          onChange={handleChange}
          required
          fullWidth
        />
        <TextField
          id="link"
          name="link"
          label="Package link"
          variant="outlined"
          margin="normal"
          inputProps={{
            maxLength: "1024",
          }}
          value={link}
          onChange={handleChange}
          required
          fullWidth
        />
        <TextField
          id="description"
          name="description"
          label="Description"
          variant="outlined"
          margin="normal"
          inputProps={{
            maxLength: "5120",
          }}
          value={description}
          onChange={handleChange}
          fullWidth
          multiline
          rows={4}
          placeholder="Package description"
        />
        <TextField
          id="releasenotes"
          name="releasenotes"
          label="Release Notes URL"
          variant="outlined"
          margin="normal"
          inputProps={{
            maxLength: "1024",
          }}
          value={releaseNotesLink}
          onChange={handleChange}
          fullWidth
          placeholder="Release Notes URL"
        />
        <Button
          type="submit"
          disabled={busy}
          fullWidth
          variant="contained"
          color="primary"
          className={classes.submit}
          onClick={onSubmit}
        >
          {busy ? "Updating..." : "Submit"}
        </Button>
      </form>
    </div>
  );
};

const UpdatePackageEditForm = () => (
  <UpdatesProvider>
    <MainForm />
  </UpdatesProvider>
);

export default UpdatePackageEditForm;
