import { ApiError } from "../../api/client";
import type { Session } from "../../api/types";
import { ConfirmDialog } from "../../components/ui/ConfirmDialog";
import { useToast } from "../../components/ui/toast-context";
import { useEndSession } from "./hooks";

interface EndSessionDialogProps {
  /** The session to end, or null when the dialog is closed. */
  session: Session | null;
  onClose: () => void;
}

/**
 * Confirm + end a live session. The relay sends a Disconnect to the agent and
 * tears down the viewer stream; for an attended session this drops the support
 * connection entirely. We confirm first because it interrupts whoever is
 * connected, then invalidate the list so the row updates.
 */
export function EndSessionDialog({ session, onClose }: EndSessionDialogProps) {
  const toast = useToast();
  const endSession = useEndSession();
  const open = session != null;

  function onConfirm() {
    if (!session) return;
    endSession.mutate(session.id, {
      onSuccess: () => {
        toast.success(
          "Session ended",
          `Disconnected ${session.agent_name}.`,
        );
        onClose();
      },
      onError: (err) => {
        toast.error(
          "Could not end session",
          err instanceof ApiError ? err.message : "The relay did not respond.",
        );
      },
    });
  }

  return (
    <ConfirmDialog
      open={open}
      title="End this session?"
      danger
      busy={endSession.isPending}
      confirmLabel="End session"
      onConfirm={onConfirm}
      onCancel={onClose}
      body={
        session ? (
          <p>
            This disconnects{" "}
            <strong>{session.agent_name}</strong> and drops any technician
            currently viewing it. {session.is_persistent
              ? "The managed agent stays enrolled and can reconnect."
              : "The support session ends and cannot be resumed."}
          </p>
        ) : null
      }
    />
  );
}
