import React, { useEffect, useRef, useState } from "react";
import { ArrowDown } from "lucide-react";

function stripAnsi(str: string): string {
  return str.replace(/\x1B\[[\d;]*[mGKHFJsu]/g, "").replace(/\x1B\][^\x07]*\x07/g, "");
}

const TIMESTAMP_RE = /^(\[\d{2}:\d{2}:\d{2}\])\s(.*)$/;

function renderLogLine(line: string, idx: number) {
  const match = line.match(TIMESTAMP_RE);
  const ts = match ? match[1] : null;
  const content = match ? match[2] : line;

  const isMarker =
    content.startsWith("--- ") &&
    (content.includes("Redeploy") || content.includes("truncated"));

  return (
    <span
      key={idx}
      className={`block ${isMarker ? "text-slate-500 dark:text-slate-500 italic" : ""}`}
    >
      {ts && (
        <span className="text-slate-400 dark:text-slate-600 select-none mr-2">
          {ts}
        </span>
      )}
      {stripAnsi(content)}
    </span>
  );
}

interface Props {
  logs: string;
  autoScroll?: boolean;
  maxHeight?: string;
}

export function LogViewer({ logs, autoScroll = true, maxHeight = "500px" }: Props) {
  const endRef = useRef<HTMLDivElement>(null);
  const [pinned, setPinned] = useState(autoScroll);

  useEffect(() => {
    if (pinned && endRef.current) {
      endRef.current.scrollIntoView({ behavior: "smooth" });
    }
  }, [logs, pinned]);

  const lines = logs.split("\n");

  return (
    <div className="relative">
      <div
        className="log-viewer bg-slate-50 dark:bg-black text-slate-800 dark:text-green-400 rounded-lg p-4 overflow-auto border border-slate-200 dark:border-gray-800 shadow-inner"
        style={{ maxHeight }}
        onScroll={(e) => {
          const el = e.currentTarget;
          const atBottom = el.scrollHeight - el.scrollTop - el.clientHeight < 50;
          setPinned(atBottom);
        }}
      >
        <pre className="ansi-stripped text-xs">
          {lines.map((line, i) => renderLogLine(line, i))}
        </pre>
        <div ref={endRef} />
      </div>
      {!pinned && (
        <button
          onClick={() => { setPinned(true); endRef.current?.scrollIntoView({ behavior: "smooth" }); }}
          className="absolute bottom-4 right-4 inline-flex items-center gap-1 text-xs bg-blue-600 text-white px-2 py-1 rounded shadow hover:bg-blue-700"
        >
          <ArrowDown size={14} /> Jump to bottom
        </button>
      )}
    </div>
  );
}
