import { cookies } from "next/headers"
import { redirect, notFound } from "next/navigation"
import { getCurrentUser } from "@/lib/auth"
import { prisma } from "@/lib/prisma"
import { SidebarProvider, SidebarInset } from "@/components/ui/sidebar"
import { AppSidebar } from "@/components/app-sidebar"
import { ChatInterface } from "@/components/chat-interface"
import { ChatHeader } from "@/components/chat-header"

interface PageProps {
  params: Promise<{ chatId: string }>
}

export default async function ChatPage({ params }: PageProps) {
  const { chatId } = await params
  const cookieStore = await cookies()
  const token = cookieStore.get("auth-token")?.value
  const user = await getCurrentUser(token)

  if (!user) {
    redirect("/login")
  }

  const chat = await prisma.chat.findFirst({
    where: { id: chatId, userId: user.id },
    include: {
      messages: {
        orderBy: { createdAt: "asc" },
      },
    },
  })

  if (!chat) {
    notFound()
  }

  const chats = await prisma.chat.findMany({
    where: { userId: user.id },
    orderBy: { updatedAt: "desc" },
    take: 100,
  })

  return (
    <SidebarProvider>
      {/* @ts-ignore */}
      <AppSidebar user={user} chats={chats} currentChatId={chatId} />
      <SidebarInset>
        <ChatHeader title={chat.title} />
        <div className="flex-1 pt-16">
          {/* @ts-ignore */}
          <ChatInterface chatId={chatId} initialMessages={chat.messages} currentUser={user} />
        </div>
      </SidebarInset>
    </SidebarProvider>
  )
}
