import CheckIcon from "@mui/icons-material/Check";
import DeleteIcon from "@mui/icons-material/Delete";
import RefreshIcon from "@mui/icons-material/Refresh";
import {
  IconButton,
  Paper,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Tooltip,
} from "@mui/material";
import React from "react";
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 { TimeWidget } from "../widgets/TimeWidget";

export function PendingDevicesRoute(): React.ReactElement {
  const loadKey = React.useRef(1);

  const [pending, setPending] = React.useState<Device[] | undefined>();

  const load = async () => {
    setPending(await DeviceApi.PendingList());
  };

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

  return (
    <SolarEnergyRouteContainer
      label="Pending devices"
      actions={
        <Tooltip title="Refresh table">
          <IconButton onClick={reload}>
            <RefreshIcon />
          </IconButton>
        </Tooltip>
      }
    >
      <AsyncWidget
        loadKey={loadKey.current}
        ready={!!pending}
        errMsg="Failed to load the list of pending devices!"
        load={load}
        build={() => (
          <PendingDevicesList onReload={reload} pending={pending!} />
        )}
      />
    </SolarEnergyRouteContainer>
  );
}

function PendingDevicesList(p: {
  pending: Device[];
  onReload: () => void;
}): React.ReactElement {
  const alert = useAlert();
  const confirm = useConfirm();
  const snackbar = useSnackbar();
  const loadingMessage = useLoadingMessage();

  const validateDevice = async (d: Device) => {
    try {
      loadingMessage.show("Validating device...");
      await DeviceApi.Validate(d);

      snackbar("The device has been successfully validated!");
      p.onReload();
    } catch (e) {
      console.error(`Failed to validate device! ${e})`);
      alert("Failed to validate device!");
    } finally {
      loadingMessage.hide();
    }
  };

  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!");
      p.onReload();
    } catch (e) {
      console.error(`Failed to delete device! ${e})`);
      alert("Failed to delete device!");
    } finally {
      loadingMessage.hide();
    }
  };

  if (p.pending.length === 0) {
    return <p>There is no device awaiting confirmation right now.</p>;
  }

  return (
    <TableContainer component={Paper}>
      <Table sx={{ minWidth: 650 }} aria-label="simple table">
        <TableHead>
          <TableRow>
            <TableCell>#</TableCell>
            <TableCell>Model</TableCell>
            <TableCell>Version</TableCell>
            <TableCell>Max number of relays</TableCell>
            <TableCell>Created</TableCell>
            <TableCell></TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {p.pending.map((dev) => (
            <TableRow key={dev.id}>
              <TableCell component="th" scope="row">
                {dev.id}
              </TableCell>
              <TableCell>{dev.info.reference}</TableCell>
              <TableCell>{dev.info.version}</TableCell>
              <TableCell>{dev.info.max_relays}</TableCell>
              <TableCell>
                <TimeWidget time={dev.time_create} />
              </TableCell>
              <TableCell>
                <Tooltip title="Validate device">
                  <IconButton onClick={() => validateDevice(dev)}>
                    <CheckIcon />
                  </IconButton>
                </Tooltip>
                <Tooltip title="Delete device">
                  <IconButton onClick={() => deleteDevice(dev)}>
                    <DeleteIcon />
                  </IconButton>
                </Tooltip>
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </TableContainer>
  );
}
