import { usePathname, useRouter } from "next/navigation";
import { ActionButton } from "@/components/ui/action-button";
import ActionConfirmingDialog from "@/components/ui/action-confirming-dialog";
import { toast } from "@/components/ui/use-toast";

import { useDeleteLabel } from "@lifetracker/shared-react/hooks/labels";

export default function DeleteLabelConfirmationDialog({
  label,
  open,
  setOpen,
}: {
  label: { id: string; code: number; name: string };
  open?: boolean;
  setOpen?: (v: boolean) => void;
}) {
  const currentPath = usePathname();
  const router = useRouter();
  const { mutate: deleteTag, isPending } = useDeleteLabel({
    onSuccess: () => {
      toast({
        description: `Label "${label.name}" has been deleted!`,
      });
      if (currentPath.includes(label.code)) {
        router.push("/dashboard/labels");
      }
    },
    onError: () => {
      toast({
        variant: "destructive",
        description: `Something went wrong`,
      });
    },
  });
  return (
    <ActionConfirmingDialog
      open={open}
      setOpen={setOpen}
      title={`Delete ${label.name}?`}
      description={`Are you sure you want to delete the label "${label.name}"?`}
      actionButton={(setDialogOpen) => (
        <ActionButton
          type="button"
          variant="destructive"
          loading={isPending}
          onClick={() =>
            deleteTag(
              { labelId: label.id },
              { onSuccess: () => setDialogOpen(false) },
            )
          }
        >
          Delete
        </ActionButton>
      )}
    />
  );
}
