import { notFound } from "next/navigation"
import { cookies } from "next/headers"
import prisma from "@/lib/prisma"
import { PlanLoginForm } from "@/components/plan-login-form"
import { Toaster } from "@/components/ui/sonner"
import { PlanDashboard } from "./_components/plan-dashboard"

export default async function DashboardPage({ params }: { params: Promise<{ planId: string }> }) {
    const { planId } = await params
    const plan = await prisma.plan.findUnique({
        where: { id: planId },
        include: { bookings: true },
    })

    if (!plan) {
        notFound()
    }

    const cookieStore = await cookies()
    const isAuthenticated = cookieStore.get(`plan_auth_${plan.id}`)?.value === "true"

    if (!isAuthenticated) {
        return (
            <main className="flex min-h-screen flex-col items-center p-4">
                <PlanLoginForm planId={plan.id} />
            </main>
        )
    }

    return (
        <main className="flex min-h-screen flex-col items-center p-4">
            <div className="w-full max-w-4xl space-y-6">
                <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
                    <div>
                        <h1 className="text-2xl font-bold">Cat Sitting Plan</h1>
                        <p className="text-muted-foreground text-sm">
                            {plan.startDate.toLocaleDateString()} - {plan.endDate.toLocaleDateString()}
                        </p>
                    </div>
                    <div className="text-sm bg-muted px-3 py-1 rounded-md">
                        Group ID: <span className="font-mono font-bold">{plan.id}</span>
                    </div>
                </div>

                <div className="p-4 border rounded-lg bg-card text-card-foreground shadow-sm">
                    <PlanDashboard plan={plan} />
                </div>
            </div>
        </main>
    )
}
