"use client";

import * as React from "react";
import { usePathname, useRouter } from "next/navigation";
import { Field, Select } from "@/components/ui/input";

/** Course switcher for the gradebook; the choice lives in the URL. */
export function GradebookPicker({
  courses,
  selectedId,
}: {
  courses: { id: string; title: string }[];
  selectedId: string;
}) {
  const router = useRouter();
  const pathname = usePathname();
  const [pending, startTransition] = React.useTransition();

  return (
    <div className="flex flex-wrap items-end gap-3 rounded-xl border border-subtle bg-surface p-4 shadow-[var(--shadow-card)]">
      <Field label="Pilih kursus" htmlFor="gradebook-course" className="w-full sm:w-80">
        <Select
          id="gradebook-course"
          value={selectedId}
          disabled={pending}
          onChange={(event) => {
            const id = event.target.value;
            startTransition(() => {
              router.replace(`${pathname}?courseId=${id}`, { scroll: false });
            });
          }}
        >
          {courses.map((course) => (
            <option key={course.id} value={course.id}>
              {course.title}
            </option>
          ))}
        </Select>
      </Field>
      {pending ? <span className="text-xs text-tertiary">Memuat…</span> : null}
    </div>
  );
}
