import { filesize } from "filesize";
import { IsoFile } from "../../api/IsoFilesApi";
import { SelectInput } from "./SelectInput";
import {
  Avatar,
  IconButton,
  ListItem,
  ListItemAvatar,
  ListItemText,
  Tooltip,
} from "@mui/material";
import DeleteIcon from "@mui/icons-material/Delete";
import { mdiDisc } from "@mdi/js";
import Icon from "@mdi/react";

export function VMSelectIsoInput(p: {
  editable: boolean;
  isoList: IsoFile[];
  attachedISOs: string[];
  onChange: (newVal: string[]) => void;
}): React.ReactElement {
  if (p.attachedISOs.length === 0 && !p.editable) return <></>;

  return (
    <>
      {p.attachedISOs.map((isoName, num) => {
        const iso = p.isoList.find((d) => d.filename === isoName);
        return (
          <ListItem
            key={isoName}
            secondaryAction={
              p.editable && (
                <IconButton
                  edge="end"
                  aria-label="Detach iso file"
                  onClick={() => {
                    p.attachedISOs.splice(num, 1);
                    p.onChange(p.attachedISOs);
                  }}
                >
                  <Tooltip title="Detach ISO file">
                    <DeleteIcon />
                  </Tooltip>
                </IconButton>
              )
            }
          >
            <ListItemAvatar>
              <Avatar>
                <Icon path={mdiDisc} />
              </Avatar>
            </ListItemAvatar>
            <ListItemText
              primary={iso?.filename}
              secondary={filesize(iso?.size ?? 0)}
            />
          </ListItem>
        );
      })}

      <SelectInput
        label="Attach an ISO file"
        editable={p.editable}
        value={undefined}
        onValueChange={(v) => {
          if (v) {
            p.attachedISOs.push(v);
            p.onChange(p.attachedISOs);
          }
        }}
        options={p.isoList.map((i) => {
          return {
            label: `${i.filename} ${filesize(i.size)}`,
            value: i.filename,
          };
        })}
      />
    </>
  );
}
