import { redirect } from "next/navigation";
import Link from "next/link";
import { getSession } from "@/lib/auth";
import { db } from "@/db";
import { annotators } from "@/db/schema";
import { eq } from "drizzle-orm";
import {
  Card,
  CardHeader,
  CardTitle,
  CardDescription,
  CardContent,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { LogoutButton } from "./logout-button";

export default async function DashboardPage() {
  const session = await getSession();
  if (!session) redirect("/");

  const [annotator] = await db
    .select({
      displayName: annotators.displayName,
      onboardedAt: annotators.onboardedAt,
    })
    .from(annotators)
    .where(eq(annotators.id, session.annotatorId))
    .limit(1);

  if (!annotator) redirect("/");

  const isOnboarded = !!annotator.onboardedAt;

  return (
    <div className="flex flex-1 items-center justify-center p-4">
      <Card className="w-full max-w-sm">
        <CardHeader className="text-center">
          <CardTitle className="text-xl">
            Welcome, {annotator.displayName}
          </CardTitle>
          <CardDescription>
            SEC cyBERT Labeling Dashboard
          </CardDescription>
        </CardHeader>
        <CardContent className="flex flex-col gap-4">
          {isOnboarded ? (
            <Link href="/quiz" className="block">
              <Button className="w-full">Start Labeling Session</Button>
            </Link>
          ) : (
            <Link href="/onboarding" className="block">
              <Button className="w-full">Complete Training</Button>
            </Link>
          )}
          <Link href="/codebook" className="block">
            <Button variant="outline" className="w-full">
              Codebook Reference
            </Button>
          </Link>
          {session.annotatorId === "admin" && (
            <Link href="/admin" className="block">
              <Button variant="outline" className="w-full">Admin Panel</Button>
            </Link>
          )}
          <LogoutButton />
        </CardContent>
      </Card>
    </div>
  );
}
