import Link from "next/link";
import { requirePermission } from "@/lib/auth/permissions";
import { getCourseFormOptions, searchCourses } from "@/lib/courses/queries";
import {
  buildCourseFinderPageHref,
  type CourseFinderSearchParams,
} from "@/lib/courses/finder-utils";
import { CourseCard } from "@/app/(app)/course-finder/course-card";
import { FinderFilters } from "@/app/(app)/course-finder/finder-filters";
import { Button } from "@/components/ui/button";

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

export default async function PartnerCourseFinderPage({
  searchParams,
}: {
  searchParams: Promise<CourseFinderSearchParams>;
}) {
  await requirePermission("course_finder", "read");

  const sp = await searchParams;
  const currentPage = Number(sp.page) || 1;

  const [options, result] = await Promise.all([
    getCourseFormOptions(),
    searchCourses({
      q: sp.q,
      country: sp.country,
      state: sp.state,
      instituteId: sp.instituteId,
      campusId: sp.campusId,
      level: sp.level,
      page: currentPage,
    }),
  ]);

  const { courses, total, page, pageSize } = result;
  const totalPages = Math.max(1, Math.ceil(total / pageSize));

  return (
    <div className="space-y-6">
      <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="font-heading text-2xl font-bold text-brand-navy">
            Course Finder
          </h1>
          <p className="mt-1 text-sm text-muted-foreground">
            Search programmes and submit student applications to EduAdvise.
          </p>
        </div>
        <Button asChild variant="outline">
          <Link href="/partner/applications">My applications</Link>
        </Button>
      </div>

      <FinderFilters options={options} basePath={BASE} />

      <p className="text-sm text-muted-foreground">
        <span className="font-semibold text-foreground">{total}</span> courses
        found
      </p>

      {courses.length === 0 ? (
        <div className="rounded-xl bg-card p-12 text-center text-sm text-muted-foreground ring-1 ring-foreground/10">
          No courses found. Try adjusting your filters.
        </div>
      ) : (
        <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
          {courses.map((c) => (
            <CourseCard key={c.id} course={c} basePath={BASE} />
          ))}
        </div>
      )}

      {total > 0 && (
        <div className="flex items-center justify-between gap-4">
          {page > 1 ? (
            <Button asChild variant="outline">
              <Link href={buildCourseFinderPageHref(BASE, sp, page - 1)}>
                Previous
              </Link>
            </Button>
          ) : (
            <Button variant="outline" disabled>
              Previous
            </Button>
          )}

          <span className="text-sm text-muted-foreground">
            Page {page} of {totalPages}
          </span>

          {page < totalPages ? (
            <Button asChild variant="outline">
              <Link href={buildCourseFinderPageHref(BASE, sp, page + 1)}>
                Next
              </Link>
            </Button>
          ) : (
            <Button variant="outline" disabled>
              Next
            </Button>
          )}
        </div>
      )}
    </div>
  );
}
