import { useState, useEffect, useRef } from "react";
import { listen } from "@tauri-apps/api/event";
import { invoke } from "@tauri-apps/api/core";

interface BackendLogsProps {
  isVisible: boolean;
  onToggle: () => void;
}

export function BackendLogs({ isVisible, onToggle }: BackendLogsProps) {
  const [logs, setLogs] = useState<string[]>([]);
  const logsEndRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    // Get existing logs on mount
    invoke<string[]>("get_backend_logs").then((existingLogs) => {
      setLogs(existingLogs);
    });

    // Listen for new log events
    const unlisten = listen<string>("backend-log", (event) => {
      setLogs((prev) => {
        const newLogs = [...prev, event.payload];
        // Keep only last 100 lines
        if (newLogs.length > 100) {
          return newLogs.slice(-100);
        }
        return newLogs;
      });
    });

    return () => {
      unlisten.then((fn) => fn());
    };
  }, []);

  useEffect(() => {
    // Auto-scroll to bottom when new logs arrive
    if (logsEndRef.current && isVisible) {
      logsEndRef.current.scrollIntoView({ behavior: "smooth" });
    }
  }, [logs, isVisible]);

  if (!isVisible) {
    return (
      <button className="logs-toggle-button" onClick={onToggle}>
        Show Backend Logs ({logs.length})
      </button>
    );
  }

  return (
    <div className="backend-logs">
      <div className="logs-header">
        <h3>Backend Logs</h3>
        <button className="logs-close-button" onClick={onToggle}>
          Hide
        </button>
      </div>
      <div className="logs-container">
        {logs.length === 0 ? (
          <p className="logs-empty">No logs yet...</p>
        ) : (
          logs.map((log, index) => (
            <pre key={index} className="log-line">
              {log}
            </pre>
          ))
        )}
        <div ref={logsEndRef} />
      </div>
    </div>
  );
}
