"use client";

import { useState, useEffect } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { ScrollArea } from "@/components/ui/scroll-area";
import { fetchAPI } from "@/lib/api";

interface ContainerLogsModalProps {
  containerId: string | null;
  containerName: string;
  endpoint: string;
  onClose: () => void;
}

export function ContainerLogsModal({
  containerId,
  containerName,
  endpoint,
  onClose,
}: ContainerLogsModalProps) {
  const [logs, setLogs] = useState<string>("");
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (!containerId) return;
    setLoading(true);
    setLogs("");
    fetchAPI<{ logs: string }>(
      `/api/containers/${endpoint}/${containerId}/logs`
    )
      .then((data) => setLogs(data.logs))
      .catch((err) => setLogs(`Error fetching logs: ${err.message}`))
      .finally(() => setLoading(false));
  }, [containerId, endpoint]);

  return (
    <Dialog open={!!containerId} onOpenChange={() => onClose()}>
      <DialogContent className="max-w-3xl">
        <DialogHeader>
          <DialogTitle className="text-sm">
            Logs: {containerName}
          </DialogTitle>
        </DialogHeader>
        <ScrollArea className="h-[400px] mt-2">
          {loading ? (
            <p className="text-xs text-muted-foreground p-4">
              Loading logs...
            </p>
          ) : (
            <pre className="text-[11px] font-mono text-foreground whitespace-pre-wrap p-2 leading-relaxed">
              {logs || "No logs available"}
            </pre>
          )}
        </ScrollArea>
      </DialogContent>
    </Dialog>
  );
}
