"use client";

import * as React from "react";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { Search, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Field, Input, Select } from "@/components/ui/input";

const TYPES = [
  { value: "", label: "Semua tipe" },
  { value: "HOMEWORK", label: "Pekerjaan Rumah" },
  { value: "PROJECT", label: "Proyek" },
  { value: "QUIZ", label: "Kuis" },
  { value: "CODING", label: "Coding" },
  { value: "EXAM", label: "Ujian" },
];

const STATUSES = [
  { value: "", label: "Semua status" },
  { value: "DRAFT", label: "Draf" },
  { value: "PUBLISHED", label: "Terbit" },
  { value: "ARCHIVED", label: "Diarsipkan" },
];

/** Filter bar for the assignment list; state lives in the URL. */
export function AssignmentFilters({
  courses,
  isStaff,
}: {
  courses: { id: string; title: string }[];
  isStaff: boolean;
}) {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();

  const [query, setQuery] = React.useState(searchParams.get("q") ?? "");
  const courseId = searchParams.get("courseId") ?? "";
  const type = searchParams.get("type") ?? "";
  const status = searchParams.get("status") ?? "";

  const push = React.useCallback(
    (patch: Record<string, string>) => {
      const params = new URLSearchParams(searchParams.toString());
      for (const [key, value] of Object.entries(patch)) {
        if (value) params.set(key, value);
        else params.delete(key);
      }
      const search = params.toString();
      router.replace(search ? `${pathname}?${search}` : pathname, { scroll: false });
    },
    [pathname, router, searchParams]
  );

  // Debounce typing so we don't push a history entry per keystroke.
  React.useEffect(() => {
    const timer = setTimeout(() => {
      if (query === (searchParams.get("q") ?? "")) return;
      push({ q: query });
    }, 350);
    return () => clearTimeout(timer);
  }, [query, push, searchParams]);

  const hasFilters = Boolean(
    query || courseId || type || (isStaff && status)
  );

  return (
    <div className="flex flex-col gap-3 rounded-xl border border-subtle bg-surface p-4 shadow-[var(--shadow-card)] lg:flex-row lg:items-end">
      <Field label="Cari tugas" htmlFor="assignment-search" className="flex-1">
        <div className="relative">
          <Search className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-tertiary" />
          <Input
            id="assignment-search"
            value={query}
            onChange={(event) => setQuery(event.target.value)}
            placeholder="Cari berdasarkan judul…"
            className="pl-9"
          />
        </div>
      </Field>

      <Field label="Kursus" htmlFor="assignment-course" className="lg:w-56">
        <Select
          id="assignment-course"
          value={courseId}
          onChange={(event) => push({ courseId: event.target.value })}
        >
          <option value="">Semua kursus</option>
          {courses.map((course) => (
            <option key={course.id} value={course.id}>
              {course.title}
            </option>
          ))}
        </Select>
      </Field>

      <Field label="Tipe" htmlFor="assignment-type" className="lg:w-44">
        <Select id="assignment-type" value={type} onChange={(event) => push({ type: event.target.value })}>
          {TYPES.map((option) => (
            <option key={option.value} value={option.value}>
              {option.label}
            </option>
          ))}
        </Select>
      </Field>

      {isStaff ? (
        <Field label="Status" htmlFor="assignment-status" className="lg:w-44">
          <Select
            id="assignment-status"
            value={status}
            onChange={(event) => push({ status: event.target.value })}
          >
            {STATUSES.map((option) => (
              <option key={option.value} value={option.value}>
                {option.label}
              </option>
            ))}
          </Select>
        </Field>
      ) : null}

      {hasFilters ? (
        <Button type="button" variant="ghost" onClick={() => router.replace(pathname, { scroll: false })}>
          <X className="size-4" />
          Reset
        </Button>
      ) : null}
    </div>
  );
}
