import { Box, Grid2 as Grid, Typography } from "@mui/material";
import { jsonBin } from "common/DataImports/BinCables/BinCableImporter";
import { useMobile } from "hooks";
import { cloneDeep } from "lodash";
import SideView from "./binSVGs/sideView";
import TopView from "./binSVGs/topView";
import CableMounting from "./cableMounting";
import CableTable from "./cableTable";

interface Props {
  bin: jsonBin;
  updateBin: (newBin: jsonBin) => void;
}

export default function CableDisplay(props: Props) {
  const { bin, updateBin } = props;
  const isMobile = useMobile();
  return (
    <Box padding={2}>
      <Typography style={{ fontSize: 20, fontWeight: 650 }}>
        {bin.Manufacturer + " " + bin.Model}
      </Typography>
      <Grid container direction="row" alignContent="center" alignItems="center" spacing={3}>
        <Grid size={isMobile ? 12 : 6}>
          <Box width="100%" paddingLeft={isMobile ? 0 : "15%"} paddingRight={isMobile ? 0 : "15%"}>
            <SideView bin={bin} />
          </Box>
        </Grid>
        <Grid size={isMobile ? 12 : 6} container direction="column">
          <Box width="100%">
            <Grid
              style={{ paddingLeft: isMobile ? 0 : "30%", paddingRight: isMobile ? 0 : "30%" }}>
              <TopView bin={bin} />
            </Grid>
            <Grid>
              <CableMounting bin={bin} />
            </Grid>
          </Box>
        </Grid>
        <Grid size={12}>
          <Box width="100%">
            <CableTable
              bin={bin}
              cablesChanged={newCables => {
                //update the json bin with the newly edited cables
                let newBin = cloneDeep(bin);
                //if the number of cables has changed will need to adjust the cable sums accordingly
                let newCounts: Map<number, number> = new Map();
                //loop through the cables to find the numbers for each orbit
                newCables.forEach(cable => {
                  let currentOrbit = newCounts.get(cable.Orbit);
                  if (currentOrbit) {
                    newCounts.set(cable.Orbit, (currentOrbit + cable.Count) as number);
                  } else {
                    newCounts.set(cable.Orbit, cable.Count);
                  }
                });
                //loop thorugh the sums setting the new counts for each orbit
                newBin.CableSums.forEach(sum => {
                  let orbitCount = newCounts.get(sum.Orbit);
                  if (orbitCount && orbitCount !== sum.NumberOfCables) {
                    sum.NumberOfCables = orbitCount;
                  }
                });
                newBin.Cables = newCables;
                updateBin(newBin);
              }}
            />
          </Box>
        </Grid>
      </Grid>
    </Box>
  );
}
