import {
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
} from "@mui/material";
import React from "react";
import { Device, DeviceApi } from "../api/DeviceApi";
import { ServerApi } from "../api/ServerApi";
import { useAlert } from "../hooks/context_providers/AlertDialogProvider";
import { useLoadingMessage } from "../hooks/context_providers/LoadingMessageProvider";
import { useSnackbar } from "../hooks/context_providers/SnackbarProvider";
import { lenValid } from "../utils/StringsUtils";
import { CheckboxInput } from "../widgets/forms/CheckboxInput";
import { TextInput } from "../widgets/forms/TextInput";

export function EditDeviceMetadataDialog(p: {
  onClose: () => void;
  device: Device;
  onUpdated: () => void;
}): React.ReactElement {
  const loadingMessage = useLoadingMessage();
  const alert = useAlert();
  const snackbar = useSnackbar();

  const [name, setName] = React.useState(p.device.name);
  const [description, setDescription] = React.useState(p.device.description);
  const [enabled, setEnabled] = React.useState(p.device.enabled);

  const onSubmit = async () => {
    try {
      loadingMessage.show("Updating device information");
      await DeviceApi.Update(p.device, {
        name,
        description,
        enabled,
      });

      snackbar("The device information have been successfully updated!");
      p.onUpdated();
    } catch (e) {
      console.error("Failed to update device general information!" + e);
      alert(`Failed to update device general information! ${e}`);
    } finally {
      loadingMessage.hide();
    }
  };

  const canSubmit =
    lenValid(name, ServerApi.Config.constraints.dev_name_len) &&
    lenValid(description, ServerApi.Config.constraints.dev_description_len);

  return (
    <Dialog open>
      <DialogTitle>Edit device general information</DialogTitle>
      <DialogContent>
        <TextInput
          editable
          label="Device name"
          value={name}
          onValueChange={(s) => setName(s ?? "")}
          size={ServerApi.Config.constraints.dev_name_len}
        />
        <TextInput
          editable
          label="Device description"
          value={description}
          onValueChange={(s) => setDescription(s ?? "")}
          size={ServerApi.Config.constraints.dev_description_len}
        />
        <CheckboxInput
          editable
          label="Enable device"
          checked={enabled}
          onValueChange={setEnabled}
        />
      </DialogContent>
      <DialogActions>
        <Button onClick={p.onClose}>Cancel</Button>
        <Button onClick={onSubmit} autoFocus disabled={!canSubmit}>
          Submit
        </Button>
      </DialogActions>
    </Dialog>
  );
}
