import { useMutation, useQueryClient } from "@tanstack/react-query";

import { publishOperation } from "../../entities/operation/api";
import { ApiError } from "../../shared/api/client";

type PublishOperationPanelProps = {
  operationId: string;
  version: number;
};

export function PublishOperationPanel({
  operationId,
  version,
}: PublishOperationPanelProps) {
  const queryClient = useQueryClient();
  const publishMutation = useMutation({
    mutationFn: async () => publishOperation(operationId, version),
    onSuccess: async () => {
      await queryClient.invalidateQueries({ queryKey: ["operations"] });
      await queryClient.invalidateQueries({
        queryKey: ["operation-summary", operationId],
      });
      await queryClient.invalidateQueries({
        queryKey: ["operation-version", operationId, version],
      });
    },
  });

  return (
    <div className="stack-layout">
      <button
        className="button-primary"
        type="button"
        onClick={() => publishMutation.mutate()}
      >
        {publishMutation.isPending ? "Publishing..." : "Publish operation"}
      </button>
      {publishMutation.data ? (
        <div className="feedback-card feedback-success">
          Published version {String(publishMutation.data.published_version)} at{" "}
          {String(publishMutation.data.published_at)}
        </div>
      ) : null}
      {publishMutation.error ? (
        <div className="feedback-card feedback-error">
          {publishMutation.error instanceof ApiError
            ? publishMutation.error.message
            : "Publish failed"}
        </div>
      ) : null}
    </div>
  );
}
