"use client";
import * as React from "react";
import { Terminal, X, Copy, Check } from "lucide-react";

export function LogViewerButton({
  title,
  content,
}: {
  title: string;
  content: string;
}) {
  const [open, setOpen] = React.useState(false);
  return (
    <>
      <button
        type="button"
        onClick={() => setOpen(true)}
        className="inline-flex items-center gap-1.5 rounded-md border border-border bg-transparent px-3 py-1.5 text-xs font-medium text-foreground/85 transition-colors hover:border-primary/40 hover:bg-primary/10 hover:text-primary"
      >
        <Terminal className="h-3 w-3" />
        Xem log
      </button>
      {open && <LogViewer title={title} content={content} onClose={() => setOpen(false)} />}
    </>
  );
}

function LogViewer({
  title,
  content,
  onClose,
}: {
  title: string;
  content: string;
  onClose: () => void;
}) {
  const scrollRef = React.useRef<HTMLDivElement>(null);
  const [copied, setCopied] = React.useState(false);

  React.useEffect(() => {
    if (scrollRef.current) {
      scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
    }
  }, []);

  React.useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") onClose();
    };
    document.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {
      document.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [onClose]);

  const onCopy = async () => {
    try {
      await navigator.clipboard.writeText(content);
      setCopied(true);
      setTimeout(() => setCopied(false), 1500);
    } catch {
      /* ignore */
    }
  };

  const cleaned = content.replace(/\x1b\[[0-9;]*[a-zA-Z]/g, "");

  return (
    <div
      role="dialog"
      aria-modal
      className="fixed inset-0 z-50 flex items-center justify-center bg-background/70 p-4 backdrop-blur-sm animate-fade-in"
      onClick={onClose}
    >
      <div
        className="flex h-[85vh] w-full max-w-5xl flex-col overflow-hidden rounded-xl border border-border bg-surface-elevated shadow-2xl"
        onClick={(e) => e.stopPropagation()}
      >
        <header className="flex items-center gap-3 border-b border-border px-5 py-3">
          <Terminal className="h-4 w-4 text-primary" />
          <h2 className="flex-1 truncate text-sm font-semibold tracking-tight">{title}</h2>
          <button
            type="button"
            onClick={onCopy}
            className="inline-flex items-center gap-1.5 rounded-md border border-border bg-transparent px-2.5 py-1.5 text-xs font-medium text-foreground/85 transition-colors hover:bg-accent"
          >
            {copied ? (
              <>
                <Check className="h-3 w-3 text-success" />
                Đã chép
              </>
            ) : (
              <>
                <Copy className="h-3 w-3" />
                Chép
              </>
            )}
          </button>
          <button
            type="button"
            onClick={onClose}
            aria-label="Đóng"
            className="rounded-md p-1.5 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
          >
            <X className="h-4 w-4" />
          </button>
        </header>
        <div ref={scrollRef} className="flex-1 overflow-auto bg-background px-5 py-4">
          <pre className="text-mono text-xs leading-relaxed text-foreground/90 whitespace-pre-wrap break-words">
            {cleaned}
          </pre>
        </div>
      </div>
    </div>
  );
}
