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[];
  value?: string;
  onChange: (newVal?: string) => void;
}): React.ReactElement {
  if (!p.value && !p.editable) return <></>;

  if (p.value) {
    const iso = p.isoList.find((d) => d.filename === p.value);
    return (
      <ListItem
        secondaryAction={
          p.editable && (
            <IconButton
              edge="end"
              aria-label="detach iso file"
              onClick={() => {
                p.onChange(undefined);
              }}
            >
              <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>
    );
  }

  return (
    <SelectInput
      label="ISO file"
      editable={p.editable}
      value={p.value}
      onValueChange={p.onChange}
      options={[
        { label: "None", value: undefined },
        ...p.isoList.map((i) => {
          return {
            label: `${i.filename} ${filesize(i.size)}`,
            value: i.filename,
          };
        }),
      ]}
    />
  );
}
