"use client";

import { use, useState, useRef } from "react";
import { ArrowLeft, Send, Loader2, Eye, RefreshCw, Trash2 } from "lucide-react";
import Link from "next/link";
import { useSession, useMessages } from "@/lib/hooks";
import { timeAgo, formatTokens, platformBadgeClass } from "@/lib/utils";
import { MessageBubble } from "@/components/MessageBubble";
import { useQueryClient } from "@tanstack/react-query";
import { useRouter } from "next/navigation";

export type Verbosity = "compact" | "normal" | "full";

const VERBOSITY_OPTIONS: { id: Verbosity; label: string }[] = [
  { id: "compact", label: "Compact" },
  { id: "normal", label: "Normal" },
  { id: "full", label: "Full" },
];

export default function SessionReplayPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = use(params);
  const qc = useQueryClient();
  const router = useRouter();
  const [confirmDelete, setConfirmDelete] = useState(false);
  const [editingTitle, setEditingTitle] = useState(false);
  const [titleDraft, setTitleDraft] = useState("");
  const { data: sessionData } = useSession(id);
  const [msgLimit, setMsgLimit] = useState(100);
  const { data: messagesData, isLoading } = useMessages(id, msgLimit);
  const [input, setInput] = useState("");
  const [sending, setSending] = useState(false);
  const [pendingMsg, setPendingMsg] = useState<string | null>(null);
  const [verbosity, setVerbosity] = useState<Verbosity>("normal");
  const [showVerbosity, setShowVerbosity] = useState(false);
  const inputRef = useRef<HTMLInputElement>(null);

  const session = sessionData?.session;
  const messages = messagesData?.items || [];

  // Filter based on verbosity
  let visibleMessages = messages.filter((m) => {
    if (m.role === "user") return true;
    if (m.role === "assistant") {
      if (verbosity === "compact") return !!m.content?.trim();
      if (verbosity === "normal") return !!m.content?.trim() || !!m.tool_calls;
      // full: show everything including tool-only and reasoning-only messages
      return true;
    }
    return false;
  }).reverse();

  const toolResults = new Map<string, { name: string; content: string }>();
  for (const m of messages) {
    if (m.role === "tool" && m.tool_call_id) {
      toolResults.set(m.tool_call_id, {
        name: m.tool_name || "tool",
        content: m.content || "",
      });
    }
  }

  const sendMessage = async () => {
    if (!input.trim() || sending) return;
    const msg = input.trim();
    setInput("");
    setSending(true);
    setPendingMsg(msg);
    try {
      await fetch("/api/sessions/" + id + "/chat", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ message: msg }),
      });
    } catch {}
    setPendingMsg(null);
    setSending(false);
    qc.invalidateQueries({ queryKey: ["messages", id] });
    qc.invalidateQueries({ queryKey: ["session", id] });
  };

  const deleteSession = async () => {
    await fetch("/api/sessions/" + id, { method: "DELETE" });
    router.push("/history");
  };

  return (
    <div className="flex flex-col" style={{ minHeight: "calc(100vh - 6rem)" }}>
      {/* Header */}
      <div className="flex items-center gap-3 mb-3">
        <Link href="/history" className="p-1 -ml-1 rounded-lg active:bg-white/[0.04]">
          <ArrowLeft size={20} style={{ color: "var(--text-2)" }} />
        </Link>
        <div className="flex-1 min-w-0">
          {editingTitle ? (
            <input
              type="text"
              value={titleDraft}
              onChange={(e) => setTitleDraft(e.target.value)}
              onBlur={async () => {
                if (titleDraft.trim() && titleDraft !== session?.title) {
                  await fetch("/api/sessions/" + id, {
                    method: "PATCH",
                    headers: { "Content-Type": "application/json" },
                    body: JSON.stringify({ title: titleDraft.trim() }),
                  });
                  qc.invalidateQueries({ queryKey: ["session", id] });
                }
                setEditingTitle(false);
              }}
              onKeyDown={(e) => { if (e.key === "Enter") (e.target as HTMLInputElement).blur(); }}
              className="text-[15px] font-medium w-full bg-transparent outline-none"
              style={{ color: "var(--text-1)", borderBottom: "1px solid var(--accent)" }}
              autoFocus
            />
          ) : (
            <div
              className="text-[15px] font-medium truncate"
              style={{ color: "var(--text-1)" }}
              onClick={() => { setTitleDraft(session?.title || ""); setEditingTitle(true); }}
            >
              {session?.title || "Session " + id.slice(0, 8)}
            </div>
          )}
          {session && (
            <div className="flex items-center gap-2 mt-0.5">
              <span className={`badge ${platformBadgeClass(session.source)}`}>
                {session.source}
              </span>
              <span className="text-[11px]" style={{ color: "var(--text-3)" }}>
                {session.model && <span className="font-mono">{session.model.split("/").pop()}</span>}
                {session.model && " · "}
                {session.message_count} msgs · {formatTokens(session.input_tokens + session.output_tokens)} · {timeAgo(session.started_at)}
              </span>
            </div>
          )}
        </div>
        {/* Delete */}
        {confirmDelete ? (
          <div className="flex items-center gap-1">
            <button
              onClick={deleteSession}
              className="px-2 py-1 rounded-lg text-[11px] font-semibold"
              style={{ background: "rgba(255,59,48,0.12)", color: "#ff3b30" }}
            >
              Delete
            </button>
            <button
              onClick={() => setConfirmDelete(false)}
              className="px-2 py-1 rounded-lg text-[11px]"
              style={{ color: "var(--text-3)" }}
            >
              Cancel
            </button>
          </div>
        ) : (
          <button
            onClick={() => setConfirmDelete(true)}
            className="p-1.5 rounded-lg active:bg-white/[0.04]"
            style={{ color: "var(--text-3)" }}
          >
            <Trash2 size={16} />
          </button>
        )}
        {/* Refresh */}
        <button
          onClick={() => { qc.invalidateQueries({ queryKey: ["messages", id] }); qc.invalidateQueries({ queryKey: ["session", id] }); }}
          className="p-1.5 rounded-lg active:bg-white/[0.04]"
          style={{ color: "var(--text-2)" }}
        >
          <RefreshCw size={16} />
        </button>
        {/* Verbosity toggle */}
        <div className="relative">
          <button
            onClick={() => setShowVerbosity(!showVerbosity)}
            className="p-1.5 rounded-lg active:bg-white/[0.04]"
            style={{ color: "var(--text-2)" }}
          >
            <Eye size={18} />
          </button>
          {showVerbosity && (
            <div
              className="absolute right-0 top-full mt-1 z-10 rounded-xl overflow-hidden"
              style={{ background: "var(--bg-raised)", border: "1px solid var(--border)" }}
            >
              {VERBOSITY_OPTIONS.map((opt) => (
                <button
                  key={opt.id}
                  onClick={() => { setVerbosity(opt.id); setShowVerbosity(false); }}
                  className="block w-full text-left px-4 py-2.5 text-[13px] transition-colors"
                  style={{
                    color: verbosity === opt.id ? "var(--accent)" : "var(--text-2)",
                    background: verbosity === opt.id ? "var(--accent-dim)" : "transparent",
                  }}
                >
                  {opt.label}
                </button>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* Message input */}
      <div className="flex gap-2 mb-4">
        <input
          ref={inputRef}
          type="text"
          value={input}
          onChange={(e) => setInput(e.target.value)}
          onKeyDown={(e) => e.key === "Enter" && sendMessage()}
          placeholder={sending ? "Hermes is thinking..." : "Send a message..."}
          className="flex-1 px-4 py-2.5 rounded-xl text-sm outline-none transition-colors"
          style={{
            background: "var(--bg-raised)",
            border: "1px solid var(--border)",
            color: "var(--text-1)",
          }}
          disabled={sending}
        />
        <button
          onClick={sendMessage}
          disabled={!input.trim() || sending}
          className="px-3 rounded-xl transition-opacity disabled:opacity-20"
          style={{ background: "var(--accent)", color: "white" }}
        >
          {sending ? <Loader2 size={16} className="animate-spin" /> : <Send size={16} />}
        </button>
      </div>

      {/* Messages */}
      {isLoading ? (
        <div className="space-y-3">
          {[...Array(4)].map((_, i) => (
            <div key={i} className="card p-4 animate-pulse">
              <div className="h-4 rounded w-full mb-2" style={{ background: "var(--bg-hover)" }} />
              <div className="h-4 rounded w-3/4" style={{ background: "var(--bg-hover)" }} />
            </div>
          ))}
        </div>
      ) : (
        <div className="space-y-2">
          {sending && (
            <div className="flex justify-start">
              <div className="rounded-2xl px-3.5 py-2.5" style={{ background: "var(--bg-raised)" }}>
                <div className="flex items-center gap-2 text-[13px]" style={{ color: "var(--text-2)" }}>
                  <Loader2 size={14} className="animate-spin" style={{ color: "var(--accent)" }} />
                  Thinking...
                </div>
              </div>
            </div>
          )}

          {pendingMsg && (
            <div className="flex justify-end">
              <div className="max-w-[88%] rounded-2xl px-3.5 py-2.5 opacity-60" style={{ background: "var(--accent)", color: "white" }}>
                <p className="text-[14px]">{pendingMsg}</p>
              </div>
            </div>
          )}

          {visibleMessages.map((m) => (
            <MessageBubble key={m.id} message={m} toolResults={toolResults} verbosity={verbosity} showTimestamp={verbosity === "full"} />
          ))}
          {visibleMessages.length === 0 && !sending && (
            <p className="text-sm py-8 text-center" style={{ color: "var(--text-3)" }}>
              Empty session
            </p>
          )}

          {/* Load more (at bottom = older messages since list is reversed) */}
          {(messagesData?.total || 0) > msgLimit && (
            <button
              onClick={() => setMsgLimit((l) => l + 100)}
              className="w-full py-3 mt-2 text-[13px] font-medium rounded-xl transition-colors"
              style={{ color: "var(--accent)", background: "var(--accent-dim)" }}
            >
              Load older messages
            </button>
          )}
        </div>
      )}
    </div>
  );
}
