import Link from "next/link";
import { notFound } from "next/navigation";
import { requirePermission } from "@/lib/auth/permissions";
import { createClient } from "@/lib/supabase/server";
import { firstIntakeMonth } from "@/lib/courses/finder-utils";
import { Button } from "@/components/ui/button";
import { PartnerCourseApplyForm } from "./apply-form";

const BASE = "/partner/course-finder";

function fmtMoney(amount: number | null, currency: string | null): string | null {
  if (amount == null) return null;
  return `${currency ?? "GBP"} ${amount.toLocaleString()}`;
}

export default async function PartnerCourseApplyPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  await requirePermission("course_finder", "read");

  const { id } = await params;
  const supabase = await createClient();

  const { data: course } = await supabase
    .from("courses")
    .select(
      "id, title, country, level, yearly_tuition_fee, currency, intake_months, intake_year, institute_id, campus_id, institute:institutes(name), campus:campuses(name)",
    )
    .eq("id", id)
    .eq("is_active", true)
    .single();

  if (!course) notFound();

  const institute = Array.isArray(course.institute)
    ? course.institute[0]
    : course.institute;
  const campus = Array.isArray(course.campus)
    ? course.campus[0]
    : course.campus;

  return (
    <div className="space-y-6">
      <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <p className="text-sm text-muted-foreground">
            <Link href={BASE} className="text-brand-blue hover:underline">
              Course Finder
            </Link>
            {" / "}
            <Link
              href={`${BASE}/${id}`}
              className="text-brand-blue hover:underline"
            >
              {course.title}
            </Link>
          </p>
          <h1 className="font-heading mt-1 text-2xl font-bold text-brand-navy">
            Apply for student
          </h1>
        </div>
        <Button asChild variant="outline">
          <Link href={`${BASE}/${id}`}>Back to course</Link>
        </Button>
      </div>

      <PartnerCourseApplyForm
        defaults={{
          courseId: course.id,
          courseTitle: course.title,
          instituteId: course.institute_id,
          instituteName: institute?.name ?? null,
          campusId: course.campus_id,
          campusName: campus?.name ?? null,
          country: course.country,
          level: course.level,
          intakeMonth: firstIntakeMonth(course.intake_months),
          intakeYear:
            course.intake_year != null ? String(course.intake_year) : "",
          tuitionLabel: fmtMoney(course.yearly_tuition_fee, course.currency),
        }}
      />
    </div>
  );
}
