import Link from "next/link";

import { PageHeader } from "@/components/layout/page-header";
import { Button } from "@/components/ui/button";
import { getCourseFormOptions, searchCourses } from "@/lib/courses/queries";

import { CourseCard } from "./course-card";
import { FinderFilters } from "./finder-filters";

type SearchParams = {
  q?: string;
  country?: string;
  state?: string;
  instituteId?: string;
  campusId?: string;
  level?: string;
  page?: string;
};

function buildPageHref(sp: SearchParams, page: number): string {
  const params = new URLSearchParams();
  if (sp.q) params.set("q", sp.q);
  if (sp.country) params.set("country", sp.country);
  if (sp.state) params.set("state", sp.state);
  if (sp.instituteId) params.set("instituteId", sp.instituteId);
  if (sp.campusId) params.set("campusId", sp.campusId);
  if (sp.level) params.set("level", sp.level);
  params.set("page", String(page));
  return `/course-finder?${params.toString()}`;
}

export default async function Page({
  searchParams,
}: {
  searchParams: Promise<SearchParams>;
}) {
  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>
      <PageHeader
        title="Course Finder"
        breadcrumb="Home / Course"
        action={
          <div className="flex flex-wrap gap-2">
            <Button asChild className="bg-brand-blue text-white hover:bg-brand-blue/90">
              <Link href="/course-finder/new">Add Course</Link>
            </Button>
            <Button asChild variant="outline">
              <Link href="/course-finder/bulk-upload">Bulk Data Upload</Link>
            </Button>
            <Button asChild variant="outline">
              <Link href="/course-finder/sample-file">Get Sample File</Link>
            </Button>
          </div>
        }
      />

      <FinderFilters options={options} />

      <p className="mb-4 text-sm text-muted-foreground">
        Total Records: <span className="font-semibold text-foreground">{total}</span>
      </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-4">
          {courses.map((c) => (
            <CourseCard key={c.id} course={c} />
          ))}
        </div>
      )}

      {total > 0 && (
        <div className="mt-6 flex items-center justify-between gap-4">
          {page > 1 ? (
            <Button asChild variant="outline">
              <Link href={buildPageHref(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={buildPageHref(sp, page + 1)}>Next</Link>
            </Button>
          ) : (
            <Button variant="outline" disabled>
              Next
            </Button>
          )}
        </div>
      )}
    </div>
  );
}
