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", "info"],
  ["AC_charging", "warning"],
];

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; // 1/7 * 100
  const range = Math.floor(percent / unit);

  return Batteries[range];
}

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

  const charging = chargingStates.find(([state]) => state === charge) || [];

  if (charging[0]) {
    Battery = BatteryCharging;
  }

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