"use client";

import { useEffect, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import {
  Loader2,
  ArrowLeft,
  Bot,
  User,
  Code2,
  Wrench,
  Download,
} from "lucide-react";
import ReactMarkdown from "react-markdown";

interface ToolCall {
  id: string;
  name: string;
  args: any;
}

interface Message {
  id: string;
  role: "user" | "assistant";
  content?: string;
  toolCalls?: ToolCall[];
  textSegments?: string[];
  createdAt: string;
}

export default function SessionViewer() {
  const params = useParams();
  const router = useRouter();
  const workspace = params.workspace as string;
  const projectId = params.projectId as string;
  const sessionId = params.sessionId as string;

  const [loading, setLoading] = useState(true);
  const [thread, setThread] = useState<any>(null);
  const [messages, setMessages] = useState<Message[]>([]);

  useEffect(() => {
    fetch(`/api/chat/threads/${sessionId}`)
      .then((r) => r.json())
      .then((d) => {
        setThread(d.thread);
        setMessages(d.messages || []);
      })
      .catch(console.error)
      .finally(() => setLoading(false));
  }, [sessionId]);

  if (loading) {
    return (
      <div className="flex-1 flex items-center justify-center bg-[#faf8f5]">
        <Loader2 className="w-5 h-5 animate-spin text-zinc-400" />
      </div>
    );
  }

  if (!thread) {
    return (
      <div className="flex-1 flex flex-col items-center justify-center bg-[#faf8f5]">
        <p className="text-zinc-500 mb-4">Session not found.</p>
        <button
          onClick={() => router.push(`/${workspace}/project/${projectId}/plan`)}
          className="text-indigo-600 font-medium text-sm hover:underline"
        >
          &larr; Back to Plan
        </button>
      </div>
    );
  }

  const exportJSON = () => {
    const exportData = {
      session_id: sessionId,
      title: thread.title,
      created_at: thread.createdAt,
      messages: messages.map((m: any) => ({
        role: m.role,
        content:
          m.content || (m.textSegments ? m.textSegments.join("\n\n") : ""),
        tool_calls: m.toolCalls
          ? m.toolCalls.map((tc: any) => {
              const rawResult = m._rawToolResults?.find(
                (tr: any) =>
                  tr.name === tc.name &&
                  JSON.stringify(tr.args) === JSON.stringify(tc.args),
              )?.result;
              return {
                name: tc.name,
                arguments: tc.args,
                result: rawResult,
              };
            })
          : undefined,
      })),
    };

    const blob = new Blob([JSON.stringify(exportData, null, 2)], {
      type: "application/json",
    });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `vibn-session-${sessionId}.json`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  return (
    <div className="flex-1 bg-[#faf8f5] overflow-y-auto flex flex-col">
      <header className="sticky top-0 bg-white border-b border-zinc-200 px-6 py-4 flex items-center gap-4 z-10">
        <button
          onClick={() => router.push(`/${workspace}/project/${projectId}/plan`)}
          className="w-8 h-8 flex items-center justify-center rounded-md hover:bg-zinc-100 text-zinc-500 transition-colors"
          title="Back to Sessions"
        >
          <ArrowLeft className="w-4 h-4" />
        </button>
        <div className="flex-1 min-w-0">
          <h1 className="text-lg font-semibold text-zinc-900 leading-none mb-1">
            {thread.title}
          </h1>
          <p className="text-xs text-zinc-500 font-mono">
            {new Date(thread.createdAt).toLocaleString()}
          </p>
        </div>
        <button
          onClick={exportJSON}
          className="flex items-center gap-2 px-3 py-1.5 bg-white border border-zinc-200 rounded-md text-sm font-medium text-zinc-700 hover:bg-zinc-50 hover:text-zinc-900 transition-colors shadow-sm"
        >
          <Download className="w-4 h-4" />
          Export JSON
        </button>
      </header>

      <div className="flex-1 max-w-4xl mx-auto w-full p-6 pb-20 space-y-8">
        {messages.map((m, i) => (
          <div key={m.id || i} className="flex gap-4">
            <div className="w-8 h-8 rounded-full flex-shrink-0 flex items-center justify-center border mt-1">
              {m.role === "user" ? (
                <div className="bg-zinc-100 border-zinc-200 w-full h-full rounded-full flex items-center justify-center">
                  <User className="w-4 h-4 text-zinc-600" />
                </div>
              ) : (
                <div className="bg-indigo-600 border-indigo-700 w-full h-full rounded-full flex items-center justify-center">
                  <Bot className="w-4 h-4 text-white" />
                </div>
              )}
            </div>

            <div className="flex-1 min-w-0 space-y-3">
              {m.role === "user" && m.content && (
                <div className="text-[15px] text-zinc-800 leading-relaxed font-medium whitespace-pre-wrap">
                  {m.content}
                </div>
              )}

              {m.role === "assistant" && (
                <>
                  {m.toolCalls && m.toolCalls.length > 0 && (
                    <div className="space-y-1.5 mb-4">
                      {m.toolCalls.map((tc, idx) => (
                        <div
                          key={idx}
                          className="bg-zinc-100 border border-zinc-200 rounded-md p-2.5 text-xs font-mono overflow-x-auto text-zinc-600"
                        >
                          <div className="flex items-center gap-2 text-zinc-800 font-semibold mb-1">
                            <Wrench className="w-3.5 h-3.5" />
                            {tc.name}
                          </div>
                          <pre className="text-[10px] leading-relaxed text-zinc-500 mt-1">
                            {JSON.stringify(tc.args, null, 2)}
                          </pre>
                        </div>
                      ))}
                    </div>
                  )}

                  {m.content && (
                    <div className="prose prose-sm prose-zinc max-w-none bg-white border border-zinc-200 p-4 rounded-xl shadow-sm">
                      <ReactMarkdown>{m.content}</ReactMarkdown>
                    </div>
                  )}

                  {/* Fallback for when textSegments exists but content is empty */}
                  {!m.content &&
                    m.textSegments &&
                    m.textSegments.length > 0 && (
                      <div className="prose prose-sm prose-zinc max-w-none bg-white border border-zinc-200 p-4 rounded-xl shadow-sm">
                        <ReactMarkdown>
                          {m.textSegments.join("\n\n")}
                        </ReactMarkdown>
                      </div>
                    )}
                </>
              )}
            </div>
          </div>
        ))}
        {messages.length === 0 && (
          <p className="text-center text-zinc-500 italic mt-10">
            Empty session.
          </p>
        )}
      </div>
    </div>
  );
}
