import { IconButton, Tooltip } from "@mui/material";
import { SolarEnergyRouteContainer } from "../widgets/SolarEnergyRouteContainer";
import FileUploadIcon from "@mui/icons-material/FileUpload";
import { UploadUpdateDialog } from "../dialogs/UploadUpdateDialog";
import React from "react";
import { OTAAPI } from "../api/OTAApi";
import { AsyncWidget } from "../widgets/AsyncWidget";

export function OTARoute(): React.ReactElement {
  const [list, setList] = React.useState<string[] | undefined>();
  const load = async () => {
    setList(await OTAAPI.SupportedPlatforms());
  };

  return (
    <AsyncWidget
      loadKey={1}
      ready={!!list}
      load={load}
      errMsg="Failed to load OTA screen!"
      build={() => <_OTARoute platforms={list!} />}
    />
  );
}

function _OTARoute(p: { platforms: Array<string> }): React.ReactElement {
  const [showUploadDialog, setShowUploadDialog] = React.useState(false);

  const reload = async () => {
    /*todo*/
  };

  return (
    <SolarEnergyRouteContainer
      label="OTA"
      actions={
        <>
          <Tooltip title="Upload a new update">
            <IconButton onClick={() => setShowUploadDialog(true)}>
              <FileUploadIcon />
            </IconButton>
          </Tooltip>
        </>
      }
    >
      {showUploadDialog && (
        <UploadUpdateDialog
          platforms={p.platforms}
          onClose={() => setShowUploadDialog(false)}
          onCreated={() => {
            setShowUploadDialog(false);
            reload();
          }}
        />
      )}
    </SolarEnergyRouteContainer>
  );
}
