import { lazy } from "react";
import {
  Tooltip
} from "@material-ui/core";
import useStyles from "../useStyles";

const Battery0 = lazy(() => import("@mui/icons-material/Battery0Bar"));
const BatteryFull = lazy(() => import("@mui/icons-material/BatteryFull"));
const BatteryUnknown = lazy(() => import("@mui/icons-material/BatteryUnknown"));
const BatteryCharging = lazy(() => import("@mui/icons-material/BatteryChargingFull"));
const Batteries = [
  lazy(() => import("@mui/icons-material/Battery0Bar")),
  lazy(() => import("@mui/icons-material/Battery1Bar")),
  lazy(() => import("@mui/icons-material/Battery2Bar")),
  lazy(() => import("@mui/icons-material/Battery3Bar")),
  lazy(() => import("@mui/icons-material/Battery4Bar")),
  lazy(() => import("@mui/icons-material/Battery5Bar")),
  lazy(() => import("@mui/icons-material/Battery6Bar")),
];

const chargingStates = [
  "V2L_trunk_active",
];

function getBatteryByPercent(percent) {
  if (isNaN(percent) || percent > 100 || percent < 0) {
    return BatteryUnknown;
  }

  if (percent === 0) {
    return Battery0;
  }

  if (percent === 100) {
    return BatteryFull;
  }

  const unit = 14.2857142857;
  const range = Math.floor(percent / unit);

  return Batteries[range];
}

export default function Battery({
  percent,
  charge = "unknown"
}) {
  const classes = useStyles();
  let Battery = getBatteryByPercent(percent);

  if (chargingStates.includes(charge)) {
    Battery = BatteryCharging;
  }

  return (
    <Tooltip title={`State: ${charge}`}>
      <div className={classes.alignCenter}>
        <Battery color="disabled" /> {percent && `${percent}%`}
      </div>
    </Tooltip>
  );
}