"use client";

import { useEffect, useRef } from "react";
import { useQuery } from "@tanstack/react-query";
import { Modal } from "@/components/ui";
import { workloads, type WorkloadKind } from "@/lib/api";

/*
 * A bounded snapshot, not a follow. The browser console already offers a real
 * terminal on the same server where `docker logs -f` works properly, with its
 * own scrollback and cancellation.
 */
export function LogDialog({
    serverId,
    kind,
    id,
    name,
    onClose,
}: {
    serverId: string;
    kind: WorkloadKind;
    id: string;
    name: string;
    onClose: () => void;
}) {
    const pre = useRef<HTMLPreElement>(null);

    const logs = useQuery({
        queryKey: ["workload-logs", serverId, kind, id],
        queryFn: () => workloads.logs(serverId, kind, id),
        refetchOnWindowFocus: false,
    });

    // Newest output is the point of the snapshot, so it opens at the bottom.
    useEffect(() => {
        if (logs.data && pre.current) pre.current.scrollTop = pre.current.scrollHeight;
    }, [logs.data]);

    return (
        <Modal open title={`Logs · ${name}`} onClose={onClose} wide>
            {logs.isLoading && <p className="text-sm text-text-secondary">Reading logs from the agent…</p>}

            {logs.isError && <p className="text-sm text-danger">{(logs.error as Error).message}</p>}

            {logs.data && (
                <>
                    {/* Stated, not implied: a truncated log must never be read as
                        a complete one. */}
                    {logs.data.truncated && (
                        <p className="mb-3 rounded border border-warning/50 px-3 py-2 text-xs text-warning">
                            Output was capped at 500 lines or 256KB, whichever came first. Older lines are not shown.
                        </p>
                    )}
                    <pre ref={pre} className="max-h-[55dvh] overflow-auto rounded border border-border bg-well p-3 font-mono text-xs text-text-primary">
                        {logs.data.text || "(no output)"}
                    </pre>
                </>
            )}
        </Modal>
    );
}
