import { Button, Grid2 as Grid, TextField } from "@mui/material";
import SearchSelect, { Option } from "common/SearchSelect";
import { GrainOptions } from "grain";
import { GrainBag } from "models/GrainBag";
import { pond } from "protobuf-ts/pond";
import { useGlobalState, useGrainBagAPI, useSnackbar } from "providers";
import React, { useState } from "react";
import { getDistanceUnit } from "utils";

interface Props {
  selectedBags: GrainBag[];
  refreshCallback: (reLoad: boolean) => void;
}

export default function BulkGrainBagSettings(props: Props) {
  const { selectedBags, refreshCallback } = props;
  const gridItemWidth = 3;
  const grainBagAPI = useGrainBagAPI();
  const { openSnack } = useSnackbar();
  const [name, setName] = useState("");
  const [length, setLength] = useState<number | undefined>(); //stored in meters
  const [diameter, setDiameter] = useState<number | undefined>(); //stored in meters
  const [grainType, setGrainType] = useState<pond.Grain | undefined>();
  const [grainOption, setGrainOption] = useState<Option | null>();
  const [customGrain, setCustomGrain] = useState<string | undefined>();
  const [variant, setVariant] = useState<string | undefined>();
  const [capacity, setCapacity] = useState<number | undefined>();
  const [bushels, setBushels] = useState<number | undefined>();
  const [fillDate, setFillDate] = useState<string | undefined>();
  const [initialMoisture, setInitialMoisture] = useState<number | undefined>();
  const [{as}] = useGlobalState();

  const convertedDistance = (enteredDistance: number) => {
    if (getDistanceUnit() === pond.DistanceUnit.DISTANCE_UNIT_FEET) {
      return enteredDistance / 3.281;
    }
    return enteredDistance;
  };

  const updateBags = () => {
    let bagsToUpdate: pond.GrainBag[] = [];
    selectedBags.forEach(b => {
      let bag = pond.GrainBag.create({
        key: b.key(),
        name: b.name(),
        settings: b.settings
      });

      if (bag.settings) {
        if (name) bag.name = name;
        if (length) bag.settings.length = convertedDistance(length);
        if (diameter) bag.settings.diameter = convertedDistance(diameter); //diameter
        if (grainType) bag.settings.supportedGrain = grainType; //grain Type
        if (customGrain) bag.settings.customGrain = customGrain; //custom grain
        if (variant) bag.settings.grainSubtype = variant; //variant
        if (capacity) bag.settings.bushelCapacity = capacity; //capacity
        if (bushels) bag.settings.currentBushels = bushels; //bushels
        if (fillDate) bag.settings.fillDate = fillDate; //fill date
        if (initialMoisture) bag.settings.initialMoisture = initialMoisture; //initial moisture
      }
    });

    grainBagAPI
      .bulkUpdateGrainBags(bagsToUpdate, as)
      .then(resp => {
        if (resp.data.successfull > 0) {
          refreshCallback(true);
          openSnack("Successfully updated " + resp.data.successfull + " bins");
        }
      })
      .catch(_err => {
        openSnack("Failed to update bins");
      });
  };

  return (
    <React.Fragment>
      <Grid container direction="row" spacing={2} alignContent="center" alignItems="center">
        {/* first row */}
        <Grid size={gridItemWidth}>
          <TextField
            fullWidth
            label="Name"
            value={name ?? ""}
            onChange={e => {
              setName(e.target.value);
            }}
          />
        </Grid>
        <Grid size={gridItemWidth}>
          <TextField
            fullWidth
            label="Length"
            type="number"
            value={length ?? ""}
            onChange={e => {
              setLength(parseFloat(e.target.value));
            }}
          />
        </Grid>
        <Grid size={gridItemWidth}>
          <TextField
            fullWidth
            label="Diameter"
            type="number"
            value={diameter ?? ""}
            onChange={e => {
              setDiameter(parseFloat(e.target.value));
            }}
          />
        </Grid>
        <Grid size={gridItemWidth}>
          <TextField
            fullWidth
            label="Capacity"
            type="number"
            value={capacity ?? ""}
            onChange={e => {
              setCapacity(parseFloat(e.target.value));
            }}
          />
        </Grid>

        {/* second row */}
        <Grid size={gridItemWidth}>
          <SearchSelect
            label="Grain Type"
            selected={grainOption}
            changeSelection={option => {
              let newGrainType = option
                ? pond.Grain[option.value as keyof typeof pond.Grain]
                : pond.Grain.GRAIN_INVALID;
              setGrainType(newGrainType);
              setGrainOption(option);
            }}
            group
            options={GrainOptions()}
          />
        </Grid>
        <Grid size={gridItemWidth}>
          <TextField
            fullWidth
            label="Grain Variant"
            value={variant ?? ""}
            onChange={e => {
              setVariant(e.target.value);
            }}
          />
        </Grid>

        <Grid size={gridItemWidth}>
          <TextField
            fullWidth
            label="Custom Grain"
            value={customGrain ?? ""}
            onChange={e => {
              setCustomGrain(e.target.value);
            }}
          />
        </Grid>
        <Grid size={gridItemWidth}>
          <TextField
            fullWidth
            label="Bushels"
            type="number"
            value={bushels ?? ""}
            onChange={e => {
              setBushels(parseFloat(e.target.value));
            }}
          />
        </Grid>

        {/* last row */}
        <Grid size={gridItemWidth}>
          <TextField
            fullWidth
            type="date"
            label="Fill Date"
            value={fillDate ?? ""}
            InputLabelProps={{ shrink: true }}
            onChange={e => setFillDate(e.target.value)}
          />
        </Grid>
        <Grid size={gridItemWidth}>
          <TextField
            fullWidth
            label="Initial Moisture"
            type="number"
            value={initialMoisture ?? ""}
            onChange={e => {
              setInitialMoisture(parseFloat(e.target.value));
            }}
          />
        </Grid>
        <Grid size={gridItemWidth}>
          <Button
            variant="contained"
            color="primary"
            onClick={() => {
              updateBags();
            }}>
            Update selected Grain Bags
          </Button>
        </Grid>
      </Grid>
    </React.Fragment>
  );
}
