import type { Instance } from "../types";
import { useEffect, useRef, useState } from "react";
import { fetchInstanceLogs, sendCommandRequest } from "../api";

type Props = {
  instance: Instance;
};

export default function InstanceConsole({ instance }: Props) {
  const [logs, setLogs] = useState<string[]>([]);
  const [command, setCommand] = useState("");
  const [autoScroll, setAutoScroll] = useState(true);
  const bottomRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
  async function poll() {
      try {
      const lines = await fetchInstanceLogs(instance.name);
      setLogs(lines);
      } catch (e) {
      console.error(e);
      }
  }

  poll();
  const interval = setInterval(poll, 2000);
  return () => clearInterval(interval);
  }, [instance.name]);

  // useEffect(() => {
  //   bottomRef.current?.scrollIntoView({ behavior: "smooth" });
  // }, [logs]);

  useEffect(() => {
    if (autoScroll) {
      bottomRef.current?.scrollIntoView({ behavior: "smooth" });
    }
  }, [logs, autoScroll]);

  async function handleSendCommand() {
    if (!command.trim()) return;
    try {
      await sendCommandRequest(instance.name, command);
      setCommand("");
    } catch (e: any) {
      console.error(e);
    }
  }

  return (
    <div className="consoleWrapper">
      <div className="consoleOutput">
        {logs.map((line, i) => <p key={i} className="consoleLine" dangerouslySetInnerHTML={{ __html: line }} />)}
        <div ref={bottomRef} />
      </div>
      <div className="consoleInput flexboxHorizontal">
        <input value={command} onChange={e => setCommand(e.target.value)}
          onKeyDown={e => { if (e.key === "Enter") handleSendCommand(); }}
          placeholder="Enter command..." />
        <button onClick={handleSendCommand}>Send</button>
        <label className="autoScrollLabel">
        <input type="checkbox" checked={autoScroll} onChange={e => setAutoScroll(e.target.checked)} />
          Auto-scroll
        </label>
      </div>
    </div>
  );
}