import {
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  List,
  ListItem,
  ListItemAvatar,
  ListItemButton,
  ListItemText,
} from "@mui/material";
import React from "react";
import { ISOCatalogEntry, IsoFilesApi } from "../api/IsoFilesApi";
import { AsyncWidget } from "../widgets/AsyncWidget";

export function IsoCatalogDialog(p: {
  open: boolean;
  onClose: () => void;
}): React.ReactElement {
  const [catalog, setCatalog] = React.useState<ISOCatalogEntry[] | undefined>();

  const load = async () => {
    setCatalog(await IsoFilesApi.Catalog());
  };

  return (
    <Dialog open={p.open} onClose={p.onClose}>
      <DialogTitle>ISO catalog</DialogTitle>
      <DialogContent>
        <AsyncWidget
          loadKey={1}
          load={load}
          errMsg="Failed to load catalog"
          build={() => <IsoCatalogDialogInner catalog={catalog!} />}
        />
      </DialogContent>
      <DialogActions>
        <Button autoFocus onClick={p.onClose}>
          Close
        </Button>
      </DialogActions>
    </Dialog>
  );
}

export function IsoCatalogDialogInner(p: {
  catalog: ISOCatalogEntry[];
}): React.ReactElement {
  return (
    <List dense>
      {p.catalog.map((entry) => (
        <a
          key={entry.name}
          href={entry.url}
          target="_blank"
          rel="noopener"
          style={{ color: "inherit", textDecoration: "none" }}
        >
          <ListItem>
            <ListItemButton>
              <ListItemAvatar>
                <img
                  src={IsoFilesApi.CatalogImageURL(entry)}
                  style={{ width: "2em" }}
                />
              </ListItemAvatar>
              <ListItemText primary={entry.name} />
            </ListItemButton>
          </ListItem>
        </a>
      ))}
    </List>
  );
}