/* eslint-disable react-x/no-array-index-key */
import AddIcon from "@mui/icons-material/Add";
import ClearIcon from "@mui/icons-material/Clear";
import {
  Alert,
  IconButton,
  InputAdornment,
  TextField,
  Tooltip,
} from "@mui/material";
import { VMInfo } from "../../api/VMApi";
import { useConfirm } from "../../hooks/providers/ConfirmDialogProvider";
import { EditSection } from "./EditSection";

export function OEMStringFormWidget(p: {
  vm: VMInfo;
  editable: boolean;
  onChange?: () => void;
}): React.ReactElement {
  const confirm = useConfirm();

  const handleDeleteOEMString = async (num: number) => {
    if (!(await confirm("Do you really want to delete this entry?"))) return;
    p.vm.oem_strings.splice(num, 1);
    p.onChange?.();
  };

  if (!p.editable && p.vm.oem_strings.length === 0) return <></>;

  return (
    <EditSection
      title="SMBIOS OEM Strings"
      actions={
        p.editable ? (
          <Tooltip title="Add a new string entry">
            <IconButton
              onClick={() => {
                p.vm.oem_strings.push("");
                p.onChange?.();
              }}
            >
              <AddIcon />
            </IconButton>
          </Tooltip>
        ) : (
          <></>
        )
      }
    >
      <Alert severity="info">
        You can use the{" "}
        <a
          href="https://www.nongnu.org/dmidecode/"
          target="_blank"
          rel="noreferrer noopener"
          style={{ color: "inherit" }}
        >
          <i>dmidecode</i>
        </a>{" "}
        tool on Linux to extract these strings on the guest.
      </Alert>

      {p.vm.oem_strings.map((s, num) => (
        <TextField
          key={num}
          fullWidth
          disabled={!p.editable}
          value={s}
          onChange={(e) => {
            p.vm.oem_strings[num] = e.target.value;
            p.onChange?.();
          }}
          style={{ marginTop: "5px" }}
          slotProps={{
            input: {
              endAdornment: p.editable ? (
                <InputAdornment position="end">
                  <Tooltip title="Remove entry">
                    <IconButton onClick={() => handleDeleteOEMString(num)}>
                      <ClearIcon />
                    </IconButton>
                  </Tooltip>
                </InputAdornment>
              ) : undefined,
            },
          }}
        />
      ))}
    </EditSection>
  );
}