import React, { useEffect, useState } from "react";
import { useParams } from "react-router";
import {
  Button,
  Chip,
  FormControl,
  Input,
  InputLabel,
  MenuItem,
  Select,
  TextField,
  Typography,
  useTheme,
} from "@material-ui/core";

import {
  UpdatesProvider,
  useUpdatesContext,
} from "../../Contexts/UpdatesContext";
import {
  useVehicleContext,
  VehicleProvider,
} from "../../Contexts/VehicleContext";
import { useUserContext } from "../../Contexts/UserContext";
import { useStatusContext } from "../../Contexts/StatusContext";
import useStyles from "../../useStyles";
import { tsLocalDateTimeString } from "../../../utils/dates";
import menuItemStyle from "../../menuItemStyle";

const MainForm = () => {
  const { packageid } = useParams();
  const { getPackages, createCarUpdates, packages, busy } = useUpdatesContext();
  const { getVehicles, vehicles } = useVehicleContext();
  const {
    token: {
      idToken: { jwtToken: token },
    },
  } = useUserContext();
  const { setMessage } = 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 [selectedVehicles, setSelectedVehicles] = useState([]);
  const classes = useStyles();
  const theme = useTheme();
  const handleVehiclesChange = (event) => {
    setSelectedVehicles(event.target.value);
  };
  const onSubmit = async (event) => {
    try {
      event.preventDefault();
      const data = {
        package_id: parseInt(packageid),
        vins: selectedVehicles,
      };
      await createCarUpdates(data, token);
      setMessage(
        `Deployed ${packageName} ${version} to ${selectedVehicles.length} cars`
      );
      setSelectedVehicles([]);
    } catch (e) {
      setMessage(e.message);
    }
  };
  const getData = async () => {
    try {
      getPackages({ id: parseInt(packageid) }, token);
    } catch (e) {
      setMessage(e.message);
    }
  };
  const handleCarOpen = async () => {
    try {
      await getVehicles(null, token);
    } catch (e) {
      setMessage(e.message);
    }
  };
  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}>
      <Typography component="h1" variant="h5">
        {`[${packageid}] ${packageName} ${version}`}
      </Typography>
      <form className={classes.form} noValidate action="{onSubmit}">
        <TextField
          label="Create Date"
          variant="filled"
          margin="normal"
          inputProps={{
            readOnly: true,
          }}
          value={createDate}
          size="small"
          fullWidth
        />
        <TextField
          id="link"
          name="link"
          label="Package link"
          variant="filled"
          margin="normal"
          inputProps={{
            readOnly: true,
          }}
          value={link}
          size="small"
          fullWidth
        />
        <TextField
          id="description"
          name="description"
          label="Description"
          variant="filled"
          margin="normal"
          inputProps={{
            readOnly: true,
          }}
          value={description}
          size="small"
          fullWidth
          multiline
          rows={4}
          placeholder="Package description"
        />
        <TextField
          id="releasenotes"
          name="releasenotes"
          label="Release Notes URL"
          variant="filled"
          margin="normal"
          inputProps={{
            readOnly: true,
          }}
          value={releaseNotesLink}
          size="small"
          fullWidth
          placeholder="Release Notes URL"
        />
        <FormControl
          className={classes.formControl}
          variant="outlined"
          fullWidth
        >
          <InputLabel htmlFor="vehicles">Vehicles</InputLabel>
          <Select
            label="Vehicles"
            placeholder="Select vehicles"
            id="vehicles"
            name="vehicles"
            multiple
            className={classes.menuProps}
            variant="outlined"
            onOpen={handleCarOpen}
            onChange={handleVehiclesChange}
            value={selectedVehicles}
            input={<Input id="select-multiple-chip" />}
            renderValue={(selected) => (
              <div className={classes.chips}>
                {selected.map((value) => (
                  <Chip key={value} label={value} className={classes.chip} />
                ))}
              </div>
            )}
          >
            {vehicles.map((vehicle) => (
              <MenuItem
                key={vehicle.vin}
                value={vehicle.vin}
                style={menuItemStyle(vehicle, selectedVehicles, theme)}
              >
                {vehicle.vin}
              </MenuItem>
            ))}
          </Select>
        </FormControl>
        <Button
          type="submit"
          disabled={busy}
          fullWidth
          variant="contained"
          color="primary"
          className={classes.submit}
          onClick={onSubmit}
        >
          {busy ? "Deploying..." : "Deploy"}
        </Button>
      </form>
    </div>
  );
};

const UpdatePackageDeployForm = () => (
  <VehicleProvider>
    <UpdatesProvider>
      <MainForm />
    </UpdatesProvider>
  </VehicleProvider>
);

export default UpdatePackageDeployForm;
