import { redirect } from "next/navigation";
import Link from "next/link";
import { getSession } from "@/lib/auth";
import { db } from "@/db";
import { annotators, quizSessions } from "@/db/schema";
import { eq, and } 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;

  // Check if user has ever passed the quiz (one-time requirement)
  const [passedQuiz] = await db
    .select({ id: quizSessions.id })
    .from(quizSessions)
    .where(
      and(
        eq(quizSessions.annotatorId, session.annotatorId),
        eq(quizSessions.passed, true),
      ),
    )
    .limit(1);

  const hasPassedQuiz = !!passedQuiz;

  // Determine the primary action link
  let primaryHref: string;
  let primaryLabel: string;
  if (!isOnboarded) {
    primaryHref = "/onboarding";
    primaryLabel = "Complete Training";
  } else if (!hasPassedQuiz) {
    primaryHref = "/quiz";
    primaryLabel = "Take Quiz";
  } else {
    primaryHref = "/label";
    primaryLabel = "Start Labeling Session";
  }

  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">
          <Link href={primaryHref} className="block">
            <Button className="w-full">{primaryLabel}</Button>
          </Link>
          <Link href="/codebook" className="block">
            <Button variant="outline" className="w-full">
              Codebook Reference
            </Button>
          </Link>
          {session.annotatorId === "joey" && (
            <Link href="/admin" className="block">
              <Button variant="outline" className="w-full">Admin Panel</Button>
            </Link>
          )}
          <LogoutButton />
        </CardContent>
      </Card>
    </div>
  );
}
