"use client";

import { use, useState, useRef, useEffect } from "react";
import { ArrowLeft, Send } 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";

export default function SessionReplayPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = use(params);
  const { data: sessionData } = useSession(id);
  const { data: messagesData, isLoading, refetch } = useMessages(id);
  const [input, setInput] = useState("");
  const [sending, setSending] = useState(false);
  const inputRef = useRef<HTMLInputElement>(null);

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

  const visibleMessages = messages.filter(
    (m) => m.role === "user" || m.role === "assistant"
  ).reverse(); // newest first

  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;
    setSending(true);
    try {
      await fetch("/api/sessions/" + id + "/chat", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ message: input.trim() }),
      });
      setInput("");
      // Poll for response
      setTimeout(() => refetch(), 2000);
      setTimeout(() => refetch(), 5000);
      setTimeout(() => refetch(), 10000);
    } catch {}
    setSending(false);
  };

  return (
    <div className="flex flex-col" style={{ minHeight: "calc(100vh - 6rem)" }}>
      {/* Header */}
      <div className="flex items-center gap-3 mb-4">
        <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">
          <div className="text-[15px] font-medium truncate" style={{ color: "var(--text-1)" }}>
            {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.message_count} msgs · {formatTokens(session.input_tokens + session.output_tokens)} · {timeAgo(session.started_at)}
              </span>
            </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="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" }}
        >
          <Send size={16} />
        </button>
      </div>

      {/* Messages - newest first */}
      {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">
          {visibleMessages.map((m) => (
            <MessageBubble key={m.id} message={m} toolResults={toolResults} />
          ))}
          {visibleMessages.length === 0 && (
            <p className="text-sm py-8 text-center" style={{ color: "var(--text-3)" }}>
              Empty session
            </p>
          )}
        </div>
      )}
    </div>
  );
}
