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

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

  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({ title: t("inventory.successes.deleted") });
    } else {
      //Check if it's an fkey violation.

      notification.error({
        title: 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} icon={<DeleteFilled />} />
      </Popconfirm>
    </RbacWrapper>
  );
}
