"use client";

import { use } from "react";
import { ArrowLeft, MessageSquare, Wrench } 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 } = useMessages(id);

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

  // Group tool results with their preceding assistant tool_calls
  const visibleMessages = messages.filter(
    (m) => m.role === "user" || m.role === "assistant"
  );

  // Collect tool results keyed by tool_call_id
  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 || "",
      });
    }
  }

  return (
    <div className="space-y-4">
      {/* Header */}
      <div className="flex items-center gap-3">
        <Link href="/history" className="p-1.5 -ml-1.5 rounded-lg active:bg-white/[0.06]">
          <ArrowLeft size={20} className="text-zinc-400" />
        </Link>
        <div className="flex-1 min-w-0">
          <h1 className="text-base font-semibold text-zinc-200 truncate">
            {session?.title || `Session ${id.slice(0, 8)}`}
          </h1>
          {session && (
            <div className="flex items-center gap-2 text-xs text-zinc-500">
              <span className={`px-1.5 py-0.5 rounded-full text-[10px] font-medium ${platformBadgeClass(session.source)}`}>
                {session.source}
              </span>
              <span>{session.message_count} msgs</span>
              <span>{formatTokens(session.input_tokens + session.output_tokens)} tok</span>
              <span>{timeAgo(session.started_at)}</span>
            </div>
          )}
        </div>
      </div>

      {/* Messages */}
      {isLoading ? (
        <div className="space-y-3">
          {[...Array(4)].map((_, i) => (
            <div key={i} className="glass p-4 animate-pulse">
              <div className="h-4 bg-white/[0.06] rounded w-full mb-2" />
              <div className="h-4 bg-white/[0.06] rounded w-3/4" />
            </div>
          ))}
        </div>
      ) : (
        <div className="space-y-3">
          {visibleMessages.map((m) => (
            <MessageBubble
              key={m.id}
              message={m}
              toolResults={toolResults}
            />
          ))}
          {visibleMessages.length === 0 && (
            <div className="glass p-6 text-center text-sm text-zinc-500">
              Empty session
            </div>
          )}
        </div>
      )}
    </div>
  );
}
