import { 
  Box, 
  Theme, 
} from "@mui/material";
import SmartBreadcrumb from "common/SmartBreadcrumb";
import { useDeviceAPI, useSnackbar } from "hooks";
import { Device } from "models";
import PageContainer from "pages/PageContainer";
import { useEffect, useState } from "react";
import { useParams } from "react-router";
import DeviceHistory from "device/DeviceHistory";
import { makeStyles } from "@mui/styles";
import { useGlobalState } from "providers";

const useStyles = makeStyles((theme: Theme) => {
  return ({
    gutter: {
      marginBottom: theme.spacing(1)
    }
  })
});

interface Props {}

export default function DeviceHistoryPage(_props: Props) {
  const classes = useStyles();
  const { error } = useSnackbar();
  const [{as}] = useGlobalState();
  const deviceAPI = useDeviceAPI();
  const deviceID = useParams<{ deviceID: string }>()?.deviceID ?? "";
  const [device, setDevice] = useState(Device.any({ settings: { deviceId: deviceID } }));
  const deviceName = device.name();

  useEffect(() => {
    (async function load() {
      await deviceAPI
        .get(deviceID, undefined, undefined, undefined, as)
        .then((response: any) => {
          setDevice(Device.any(response.data));
        })
        .catch((err: any) => {
          error(err);
        });
    })();
  }, [deviceAPI, deviceID, error]);

  return (
    <PageContainer>
      <Box className={classes.gutter}>
        <SmartBreadcrumb deviceName={deviceName} />
      </Box>
      <DeviceHistory device={device} />
    </PageContainer>
  );
}
