import React from "react";
import { AsyncWidget } from "../widgets/AsyncWidget";
import { SolarEnergyRouteContainer } from "../widgets/SolarEnergyRouteContainer";
import { Device, DeviceApi } from "../api/DeviceApi";
import {
  TableContainer,
  Paper,
  Table,
  TableHead,
  TableRow,
  TableCell,
  TableBody,
} from "@mui/material";
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">
      <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 {
  return (
    <TableContainer component={Paper}>
      <Table sx={{ minWidth: 650 }} aria-label="simple table">
        <TableHead>
          <TableRow>
            <TableCell>#</TableCell>
            <TableCell>Model</TableCell>
            <TableCell>Version</TableCell>
            <TableCell>Maximum number of relays</TableCell>
            <TableCell>Created</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>
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </TableContainer>
  );
}
