import { DeleteFilled } from "@ant-design/icons";
import { useMutation } from "@apollo/client";
import { Button, notification, Popconfirm } from "antd";
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { DELETE_INVENTORY_LINE } from "../../graphql/inventory.queries";
import RbacWrapper from "../rbac-wrapper/rbac-wrapper.component";

export default function InventoryLineDelete({
  inventoryline,
  disabled,
  refetch,
}) {
  const [loading, setLoading] = useState(false);
  const { t } = useTranslation();
  const [deleteInventoryLine] = useMutation(DELETE_INVENTORY_LINE);

  const handleDelete = async () => {
    setLoading(true);
    const result = await deleteInventoryLine({
      variables: { lineId: inventoryline.id },
      //   update(cache, { errors }) {
      //     cache.modify({
      //       fields: {
      //         inventory(existingInventory, { readField }) {
      //           console.log(existingInventory);
      //           return existingInventory.filter(
      //             (invRef) => inventoryline.id !== readField("id", invRef)
      //           );
      //         },
      //       },
      //     });
      //   },
    });

    if (!!!result.errors) {
      notification["success"]({ message: t("inventory.successes.deleted") });
    } else {
      //Check if it's an fkey violation.

      notification["error"]({
        message: t("bills.errors.deleting", {
          error: JSON.stringify(result.errors),
        }),
      });
    }
    if (refetch) refetch();
    setLoading(false);
  };

  return (
    <RbacWrapper action="inventory:delete" noauth={<></>}>
      <Popconfirm
        disabled={disabled || inventoryline.consumedbybillid}
        onConfirm={handleDelete}
        title={t("inventory.labels.deleteconfirm")}
      >
        <Button
          disabled={disabled || inventoryline.consumedbybillid}
          loading={loading}
        >
          <DeleteFilled />
        </Button>
      </Popconfirm>
    </RbacWrapper>
  );
}
