import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import Link from "next/link";
import ChatView from "./ChatView";
import Layout from "../../../components/Layout";

async function getAuthState() {
  const baseUrl = process.env.INTERNAL_API_URL || process.env.NEXT_PUBLIC_API_BASE_URL || "http://127.0.0.1:18000";
  const cookieStore = await cookies();
  const sessionCookie = cookieStore.get("ai_chat_session");
  
  if (!sessionCookie) return null;
  
  try {
    const res = await fetch(`${baseUrl}/api/auth/me`, {
      headers: {
        Cookie: `${sessionCookie.name}=${sessionCookie.value}`
      },
      cache: "no-store",
    });
    if (!res.ok) return null;
    return await res.json();
  } catch {
    return null;
  }
}

async function getChat(id: string) {
  const baseUrl = process.env.INTERNAL_API_URL || process.env.NEXT_PUBLIC_API_BASE_URL || "http://127.0.0.1:18000";
  const cookieStore = await cookies();
  const sessionCookie = cookieStore.get("ai_chat_session");
  
  if (!sessionCookie) return null;
  
  try {
    const res = await fetch(`${baseUrl}/api/chats/${id}`, {
      headers: {
        Cookie: `${sessionCookie.name}=${sessionCookie.value}`
      },
      cache: "no-store",
    });
    if (!res.ok) return null;
    return await res.json();
  } catch {
    return null;
  }
}

async function getMessages(id: string) {
  const baseUrl = process.env.INTERNAL_API_URL || process.env.NEXT_PUBLIC_API_BASE_URL || "http://127.0.0.1:18000";
  const cookieStore = await cookies();
  const sessionCookie = cookieStore.get("ai_chat_session");
  
  if (!sessionCookie) return [];
  
  try {
    const res = await fetch(`${baseUrl}/api/chats/${id}/messages`, {
      headers: {
        Cookie: `${sessionCookie.name}=${sessionCookie.value}`
      },
      cache: "no-store",
    });
    if (!res.ok) return [];
    return await res.json();
  } catch {
    return [];
  }
}

async function getChats() {
  const baseUrl = process.env.INTERNAL_API_URL || process.env.NEXT_PUBLIC_API_BASE_URL || "http://127.0.0.1:18000";
  const cookieStore = await cookies();
  const sessionCookie = cookieStore.get("ai_chat_session");
  
  if (!sessionCookie) return [];
  
  try {
    const res = await fetch(`${baseUrl}/api/chats`, {
      headers: { Cookie: `${sessionCookie.name}=${sessionCookie.value}` },
      cache: "no-store",
    });
    if (!res.ok) return [];
    return await res.json();
  } catch {
    return [];
  }
}

export default async function ChatPage({ params }: { params: Promise<{ id: string }> }) {
  const auth = await getAuthState();
  if (!auth) {
    redirect("/login");
  }

  const { id } = await params;

  const chat = await getChat(id);
  if (!chat) {
    return (
      <main style={{ padding: 24, fontFamily: "Arial, sans-serif" }}>
        <h1>Chat Not Found</h1>
        <Link href="/">Back to Home</Link>
      </main>
    );
  }

  const messages = await getMessages(id);
  const chats = await getChats();

  return (
    <Layout chats={chats} user={auth}>
      <ChatView chat={chat} initialMessages={messages} />
    </Layout>
  );
}
