import { InputNumber } from "antd";
import { useState } from "react";
import { useMutation } from "@apollo/client/react";
import { useTranslation } from "react-i18next";
import { UPDATE_ASSOCIATION } from "../../graphql/user.queries";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

export default function ShopUsersAuthEdit({ association }) {
  const { t } = useTranslation();
  const [updateAssociation] = useMutation(UPDATE_ASSOCIATION);
  const [open, setOpen] = useState(false);
  const [value, setValue] = useState(association.authlevel);
  const notification = useNotification();

  const handleSave = async () => {
    setOpen(false);
    const result = await updateAssociation({
      variables: {
        assocId: association.id,
        assoc: { authlevel: value }
      }
    });

    if (result.errors) {
      notification.error({
        title: t("user.errors.updating", {
          message: JSON.stringify(result.errors)
        })
      });
    }
  };

  return (
    <div>
      {open && (
        <div>
          <InputNumber
            min={0}
            value={value}
            onChange={(val) => setValue(val)}
            defaultValue={association.authlevel}
            onBlur={handleSave}
          />
        </div>
      )}
      {!open && <div style={{ cursor: "pointer" }}>{association.authlevel || t("general.labels.na")}</div>}
    </div>
  );
}
