import DeleteIcon from "@mui/icons-material/Delete";
import { IconButton, Tooltip } from "@mui/material";
import React from "react";
import { useNavigate, useParams } from "react-router-dom";
import { Device, DeviceApi } from "../../api/DeviceApi";
import { useAlert } from "../../hooks/context_providers/AlertDialogProvider";
import { useConfirm } from "../../hooks/context_providers/ConfirmDialogProvider";
import { useLoadingMessage } from "../../hooks/context_providers/LoadingMessageProvider";
import { useSnackbar } from "../../hooks/context_providers/SnackbarProvider";
import { AsyncWidget } from "../../widgets/AsyncWidget";
import { SolarEnergyRouteContainer } from "../../widgets/SolarEnergyRouteContainer";
import { GeneralDeviceInfo } from "./GeneralDeviceInfo";
import { DeviceRelays } from "./DeviceRelays";
import Grid from "@mui/material/Grid2";

export function DeviceRoute(): React.ReactElement {
  const { id } = useParams();
  const [device, setDevice] = React.useState<Device | undefined>();

  const loadKey = React.useRef(1);

  const load = async () => {
    setDevice(await DeviceApi.GetSingle(id!));
  };

  const reload = () => {
    loadKey.current += 1;
    setDevice(undefined);
  };

  return (
    <AsyncWidget
      loadKey={loadKey.current}
      errMsg="Failed to load device information"
      load={load}
      ready={!!device}
      build={() => <DeviceRouteInner device={device!} onReload={reload} />}
    />
  );
}

function DeviceRouteInner(p: {
  device: Device;
  onReload: () => void;
}): React.ReactElement {
  const alert = useAlert();
  const confirm = useConfirm();
  const snackbar = useSnackbar();
  const loadingMessage = useLoadingMessage();
  const navigate = useNavigate();

  const deleteDevice = async (d: Device) => {
    try {
      if (
        !(await confirm(
          `Do you really want to delete the device ${d.id}? The operation cannot be reverted!`
        ))
      )
        return;

      loadingMessage.show("Deleting device...");
      await DeviceApi.Delete(d);

      snackbar("The device has been successfully deleted!");
      navigate("/devices");
    } catch (e) {
      console.error(`Failed to delete device! ${e})`);
      alert("Failed to delete device!");
    } finally {
      loadingMessage.hide();
    }
  };
  return (
    <SolarEnergyRouteContainer
      label={`Device ${p.device.name}`}
      actions={
        <Tooltip title="Delete device">
          <IconButton onClick={() => deleteDevice(p.device)}>
            <DeleteIcon />
          </IconButton>
        </Tooltip>
      }
    >
      <Grid container spacing={2}>
        <Grid size={{ xs: 12, md: 6 }}>
          <GeneralDeviceInfo {...p} />
        </Grid>
        <Grid size={{ xs: 12, md: 6 }}>
          <DeviceRelays {...p} />
        </Grid>
      </Grid>
    </SolarEnergyRouteContainer>
  );
}
