import { Grid2 } from "@mui/material";
import { Device, User } from "models";
import { getContextKeys, getContextTypes } from "pbHelpers/Context";
import { useDeviceAPI, useGlobalState, useSnackbar } from "providers";
import { useEffect, useState } from "react";
import { useLocation, useParams } from "react-router-dom";
import PageContainer from "./PageContainer";
import { useMobile } from "hooks";
import LoadingScreen from "app/LoadingScreen";
import SmartBreadcrumb from "common/SmartBreadcrumb";
import DeviceActions from "common/DeviceActions";
import { pond } from "protobuf-ts/pond";
import { cloneDeep } from "lodash";
import DeviceOverview from "device/DeviceOverview";

// const useStyles = makeStyles((theme: Theme) => {
//   // const isMobile = useMobile()
//   return ({
    
//   });
// });

export default function DevicePage() {
  const deviceAPI = useDeviceAPI()
  const snackbar = useSnackbar()
  const isMobile = useMobile()
  const deviceID = useParams<{ deviceID: string }>()?.deviceID ?? "";
  const { state } = useLocation();
  const [{ as, team, user }] = useGlobalState()
  const [device, setDevice] = useState<Device>(state?.device ? Device.create(state.device) : Device.create())
  const [loading, setLoading] = useState(false)
  const [permissions, setPermissions] = useState<pond.Permission[]>([])
  const [preferences, setPreferences] = useState<pond.DevicePreferences>(pond.DevicePreferences.create())

  const [cellularUsage, setCellularUsage] = useState<number>(0);
  const [cellularStatus, setCellularStatus] = useState<string>("");

  const loadDevice = () => {
    if (loading) return
    // if (state?.device && parseInt(state.device.settings.deviceId) === device.id()) return
    // deviceAPI.get(deviceID, false, getContextKeys(), getContextTypes()).then(resp => {
    //   setDevice(Device.create(resp.data))
    //   console.log(resp.data)
    // }).catch(() => {
    //   snackbar.error("Error loading device.")
    // }).finally(() => {
    //   setLoading(false)
    // })

    setLoading(true)
    deviceAPI.getPageData(deviceID, getContextKeys(), getContextTypes()).then(resp => {
      setDevice(Device.any(resp.data.device))
      setPermissions(resp.data.permissions)
      let u = User.any(resp.data.user);
      setPreferences(u.preferences)
    }).catch(err => {
      setDevice(Device.create());
      // setComponents(new Map());
      // setInteractions([]);
      // setAvailablePositions(new Map());
      setPermissions([]);
      setPreferences(pond.UserPreferences.create());
      // setInvalidDevice(true);
      // error(err);
      if (err?.response?.data?.error.includes("not found")) {
        let name = as === team.key() ? team.name() : user.name();
        let warningString = name + " not permitted to view Device " + deviceID;
        let length = getContextTypes().length;
        if (length > 0) {
          warningString = warningString + " through " + getContextTypes()[length - 1];
        }
        snackbar.warning(warningString);
      } else {
        snackbar.error(err);
      }
    })
    .finally(() => setLoading(false));
  }

  useEffect(() => {
    loadDevice()
  }, [deviceID])

  const toggleNotificationPreference = () => {
    let updatedPreferences = cloneDeep(preferences);
    updatedPreferences.notify = !preferences.notify;
    deviceAPI
      .updatePreferences(deviceID, updatedPreferences, getContextKeys(), getContextTypes())
      .then(() => setPreferences(updatedPreferences))
      .catch(() => {
        snackbar.error(
          "Error occured while " +
            (preferences.notify ? "enabling" : "disabling") +
            " notifications"
        );
      });
  };

  if (loading) return (
    <LoadingScreen message="Loading device"/>
  )

  const getUsage = () => {
    let usage = undefined;
    if (cellularStatus && cellularStatus !== "") {
      usage = { status: cellularStatus, bytes: cellularUsage };
    }
    return usage;
  };

  return (
    <PageContainer padding={isMobile ? 0 : 2}>
      {/* <Typography>
        {device.name()}
      </Typography> */}
      <Grid2 container justifyContent={"space-between"}>
        <Grid2>
          <SmartBreadcrumb />
        </Grid2>
        <Grid2>
        <DeviceActions
          device={device}
          isPaused={false}
          isLoading={loading}
          permissions={permissions}
          preferences={preferences}
          toggleNotificationPreference={toggleNotificationPreference}
          refreshCallback={loadDevice}
        />
        </Grid2>
      </Grid2>
      <DeviceOverview
        device={device}
        // components={[...components.values()]}
        components={[]}
        usage={getUsage()}
        loading={loading}
      />
    </PageContainer>
  );
}