"use client";

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

const LEVELS = [
  { value: "", label: "Semua tingkat" },
  { value: "BEGINNER", label: "Pemula" },
  { value: "INTERMEDIATE", label: "Menengah" },
  { value: "ADVANCED", label: "Mahir" },
];

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

/**
 * Course list filters.
 *
 * State lives in the URL (`?q=&level=&status=`) so results are shareable and
 * the server component re-queries on every change — no client-side filtering of
 * an already-fetched list.
 */
export function CourseFilters({
  initial,
  showStatus,
}: {
  initial: { q: string; status: string; level: string };
  showStatus: boolean;
}) {
  const router = useRouter();
  const pathname = usePathname();
  const [query, setQuery] = React.useState(initial.q);
  const [level, setLevel] = React.useState(initial.level);
  const [status, setStatus] = React.useState(initial.status);

  // Debounce typing so we don't push a history entry per keystroke.
  React.useEffect(() => {
    const timer = setTimeout(() => {
      if (query === initial.q) return;
      push({ q: query, level, status });
    }, 350);
    return () => clearTimeout(timer);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [query]);

  function push(next: { q?: string; level?: string; status?: string }) {
    const params = new URLSearchParams();
    const q = next.q ?? query;
    const lv = next.level ?? level;
    const st = next.status ?? status;
    if (q.trim()) params.set("q", q.trim());
    if (lv) params.set("level", lv);
    if (st) params.set("status", st);
    const search = params.toString();
    router.replace(search ? `${pathname}?${search}` : pathname, { scroll: false });
  }

  const hasFilters = Boolean(query.trim() || level || (showStatus && status));

  return (
    <div className="flex flex-col gap-3 rounded-xl border border-subtle bg-surface p-4 shadow-[var(--shadow-card)] sm:flex-row sm:items-end">
      <Field label="Cari kursus" htmlFor="course-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="course-search"
            value={query}
            onChange={(event) => setQuery(event.target.value)}
            placeholder="Cari berdasarkan judul atau ringkasan…"
            className="pl-9"
          />
        </div>
      </Field>

      <Field label="Tingkat" htmlFor="course-level" className="sm:w-44">
        <Select
          id="course-level"
          value={level}
          onChange={(event) => {
            setLevel(event.target.value);
            push({ level: event.target.value });
          }}
        >
          {LEVELS.map((option) => (
            <option key={option.value} value={option.value}>
              {option.label}
            </option>
          ))}
        </Select>
      </Field>

      {showStatus ? (
        <Field label="Status" htmlFor="course-status" className="sm:w-44">
          <Select
            id="course-status"
            value={status}
            onChange={(event) => {
              setStatus(event.target.value);
              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={() => {
            setQuery("");
            setLevel("");
            setStatus("");
            router.replace(pathname, { scroll: false });
          }}
        >
          <X className="size-4" />
          Reset
        </Button>
      ) : null}
    </div>
  );
}
