import {
  Button,
  DialogActions,
  DialogContent,
  DialogTitle,
  Grid2 as Grid,
  MenuItem,
  TextField
} from "@mui/material";
import ResponsiveDialog from "common/ResponsiveDialog";
import { useComponentAPI, useSnackbar } from "hooks";
import { Component } from "models";
import { pond } from "protobuf-ts/pond";
import { useGlobalState } from "providers";
// import { MatchParams } from "navigation/Routes";
// import { useRouteMatch } from "react-router";
import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";

interface Props {
  open: boolean;
  newChart?: boolean;
  closeDialog: () => void;
  component: Component;
  mutation?: pond.Mutator;
  currentMin: number | string;
  currentMax: number | string;
  adjustMin: (val: number) => void;
  adjustMax: (val: number) => void;
}

export default function GraphSettings(props: Props) {
  const {
    open,
    component,
    mutation,
    closeDialog,
    adjustMin,
    adjustMax,
    currentMin,
    currentMax,
    newChart
  } = props;
  const [{as}] = useGlobalState();
  const [newMutation, setNewMutation] = useState<pond.Mutator>(0);
  const componentAPI = useComponentAPI();
  const deviceID = useParams<{ deviceID: string }>()?.deviceID ?? "";
  const { openSnack } = useSnackbar();

  useEffect(() => {
    if (mutation !== undefined) {
      setNewMutation(mutation);
    }
  }, [mutation]);

  const saveMutation = () => {
    let comp = component;
    let defaultMutations = comp.settings.defaultMutations;
    if (!defaultMutations.includes(newMutation) && newMutation !== pond.Mutator.MUTATOR_NONE) {
      defaultMutations.push(newMutation);
    }
    componentAPI
      .update(parseInt(deviceID), comp.settings, undefined, undefined, as)
      .then(() => openSnack("Mutations Updated"));
    closeDialog();
  };

  const deleteDerivedChart = () => {
    let comp = component;
    let defaultMuts = comp.settings.defaultMutations;
    if (mutation && defaultMuts.includes(mutation)) {
      defaultMuts.splice(defaultMuts.indexOf(mutation));
    }
    componentAPI
      .update(parseInt(deviceID), comp.settings, undefined, undefined, as)
      .then(() => openSnack("Mutations Updated"));
    closeDialog();
  };

  const handleChange = (event: any) => {
    setNewMutation(event.target.value as pond.Mutator);
  };

  return (
    <ResponsiveDialog open={open} onClose={closeDialog}>
      <DialogTitle>Chart Settings</DialogTitle>
      <DialogContent>
        {newChart && (
          <TextField select fullWidth value={newMutation} onChange={handleChange}>
            {/* TODO: change the menu item to be from the available mutations in the component settings (doesn't exist yet) */}
            <MenuItem value={pond.Mutator.MUTATOR_NONE}>None</MenuItem>
            <MenuItem value={pond.Mutator.MUTATOR_EMC}>Grain Moisture(EMC)</MenuItem>
            <MenuItem value={pond.Mutator.MUTATOR_CFM}>CFM</MenuItem>
          </TextField>
        )}
        {!newChart && (
          <Grid container direction="column">
            <Grid>
              <TextField
                label="Min Range"
                type="number"
                fullWidth
                defaultValue={currentMin}
                onChange={e => adjustMin(parseInt(e.target.value))}
              />
            </Grid>
            <Grid>
              <TextField
                label="Max Range"
                type="number"
                fullWidth
                defaultValue={currentMax}
                onChange={e => adjustMax(parseInt(e.target.value))}
              />
            </Grid>
          </Grid>
        )}
      </DialogContent>
      <DialogActions>
        {mutation !== undefined && mutation > pond.Mutator.MUTATOR_NONE && (
          <Button onClick={deleteDerivedChart} variant="contained" style={{ background: "red" }}>
            Delete
          </Button>
        )}
        <Button onClick={closeDialog} variant="contained" color="primary">
          Close
        </Button>
        {mutation === pond.Mutator.MUTATOR_NONE && (
          <Button variant="contained" onClick={saveMutation} color="primary">
            Save
          </Button>
        )}
      </DialogActions>
    </ResponsiveDialog>
  );
}
