import Link from "next/link";
import { requireUser } from "@/lib/auth/session";
import { requireCompleteStudentProfile } from "@/lib/auth/student-onboarding";
import { createClient } from "@/lib/supabase/server";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { APPLICATION_STATUS_STYLES } from "@/lib/applications/constants";

function oneField(
  rel: { [k: string]: unknown } | { [k: string]: unknown }[] | null | undefined,
  key: string,
): string {
  if (!rel) return "";
  const r = Array.isArray(rel) ? rel[0] : rel;
  const v = r?.[key];
  return v != null ? String(v) : "";
}

type PortalApplication = {
  id: string;
  applicant_name: string;
  status: string;
  country: string | null;
  intake_month: string | null;
  intake_year: number | null;
  institute: { name: string } | { name: string }[] | null;
  course: { title: string } | { title: string }[] | null;
};

export default async function PortalDashboardPage() {
  const user = await requireUser();
  if (user.role?.slug === "student") {
    await requireCompleteStudentProfile(user.id);
  }
  const supabase = await createClient();

  // RLS scopes a student to their own rows; we also filter explicitly.
  const { data } = await supabase
    .from("student_applications")
    .select("*, institute:institutes(name), course:courses(title)")
    .eq("student_user_id", user.id)
    .order("created_at", { ascending: false });

  const applications = (data as PortalApplication[] | null) ?? [];

  return (
    <div className="space-y-8">
      <div>
        <p className="eyebrow text-brand-orange">Student Portal</p>
        <h1 className="font-heading text-2xl font-bold text-brand-navy">
          Welcome, {user.full_name}
        </h1>
        <p className="mt-1 text-sm text-muted-foreground">
          Track the status of your study-abroad applications below.
        </p>
      </div>

      {applications.length === 0 ? (
        <Card>
          <CardContent className="flex flex-col items-center gap-2 py-12 text-center">
            <p className="text-base font-medium text-brand-navy">
              No applications linked yet
            </p>
            <p className="max-w-sm text-sm text-muted-foreground">
              No applications linked yet — your counselor will set this up.
            </p>
          </CardContent>
        </Card>
      ) : (
        <div className="grid gap-4 sm:grid-cols-2">
          {applications.map((app) => {
            const institute = oneField(app.institute, "name");
            const course = oneField(app.course, "title");
            const statusStyle =
              APPLICATION_STATUS_STYLES[app.status] ??
              "bg-gray-100 text-gray-800";
            const intake = [app.intake_month, app.intake_year]
              .filter(Boolean)
              .join(" ");

            return (
              <Card key={app.id} className="flex flex-col">
                <CardHeader className="pb-3">
                  <div className="flex items-start justify-between gap-3">
                    <CardTitle className="text-base text-brand-navy">
                      {institute || app.applicant_name}
                    </CardTitle>
                    <Badge className={statusStyle}>{app.status}</Badge>
                  </div>
                  {course ? (
                    <p className="text-sm text-muted-foreground">{course}</p>
                  ) : null}
                </CardHeader>
                <CardContent className="flex flex-1 flex-col justify-between gap-4">
                  <dl className="space-y-1 text-sm">
                    {app.country ? (
                      <div className="flex justify-between gap-4">
                        <dt className="text-muted-foreground">Country</dt>
                        <dd className="font-medium">{app.country}</dd>
                      </div>
                    ) : null}
                    {intake ? (
                      <div className="flex justify-between gap-4">
                        <dt className="text-muted-foreground">Intake</dt>
                        <dd className="font-medium">{intake}</dd>
                      </div>
                    ) : null}
                  </dl>
                  <Button
                    asChild
                    variant="outline"
                    className="w-full"
                  >
                    <Link href={`/portal/applications/${app.id}`}>
                      View status
                    </Link>
                  </Button>
                </CardContent>
              </Card>
            );
          })}
        </div>
      )}
    </div>
  );
}
