import { redirect } from "next/navigation";
import { requireUser } from "@/lib/auth/session";
import { createClient } from "@/lib/supabase/server";
import { OnboardingForm } from "./onboarding-form";

export default async function StudentOnboardingPage({
  searchParams,
}: {
  searchParams: Promise<{ app?: string }>;
}) {
  const user = await requireUser();
  const { app: appId } = await searchParams;
  const supabase = await createClient();

  let application: {
    id: string;
    applicant_name: string;
    phone: string | null;
    country: string | null;
  } | null = null;

  if (appId) {
    const { data } = await supabase
      .from("student_applications")
      .select("id, applicant_name, phone, country, profile_completed_at")
      .eq("id", appId)
      .eq("student_user_id", user.id)
      .is("profile_completed_at", null)
      .maybeSingle();
    application = data;
  } else {
    const { data } = await supabase
      .from("student_applications")
      .select("id, applicant_name, phone, country, profile_completed_at")
      .eq("student_user_id", user.id)
      .is("profile_completed_at", null)
      .order("created_at", { ascending: false })
      .limit(1)
      .maybeSingle();
    application = data;
  }

  if (!application) {
    redirect("/portal");
  }

  return (
    <div className="space-y-6">
      <div>
        <p className="eyebrow text-brand-orange">One more step</p>
        <h1 className="font-heading text-2xl font-bold text-brand-navy">
          Complete your profile
        </h1>
        <p className="mt-1 text-sm text-muted-foreground">
          EduAdvise needs a few details before you can track your application.
        </p>
      </div>
      <OnboardingForm
        applicationId={application.id}
        applicantName={application.applicant_name}
        defaults={{
          phone: application.phone,
          country: application.country,
        }}
      />
    </div>
  );
}
