"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";
import { ROLE_LABELS } from "@/lib/roles";

const ROLES = [
  { value: "", label: "Semua peran" },
  { value: "ADMIN", label: ROLE_LABELS.ADMIN },
  { value: "TEACHER", label: ROLE_LABELS.TEACHER },
  { value: "STUDENT", label: ROLE_LABELS.STUDENT },
];

const STATUSES = [
  { value: "", label: "Semua status" },
  { value: "ACTIVE", label: "Aktif" },
  { value: "SUSPENDED", label: "Ditangguhkan" },
  { value: "PENDING", label: "Menunggu" },
];

/**
 * User directory filters.
 *
 * Filter state lives in the URL (`?q=&role=&status=`) so the server component
 * re-queries on every change instead of the client filtering a fetched list.
 */
export function UserFilters({
  initial,
}: {
  initial: { q: string; role: string; status: string };
}) {
  const router = useRouter();
  const pathname = usePathname();
  const [query, setQuery] = React.useState(initial.q);
  const [role, setRole] = React.useState(initial.role);
  const [status, setStatus] = React.useState(initial.status);

  React.useEffect(() => {
    const timer = setTimeout(() => {
      if (query === initial.q) return;
      push({ q: query });
    }, 350);
    return () => clearTimeout(timer);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [query]);

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

  const hasFilters = Boolean(query.trim() || role || 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 pengguna" htmlFor="user-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="user-search"
            value={query}
            onChange={(event) => setQuery(event.target.value)}
            placeholder="Cari nama, username, atau email…"
            className="pl-9"
          />
        </div>
      </Field>

      <Field label="Peran" htmlFor="user-role" className="sm:w-44">
        <Select
          id="user-role"
          value={role}
          onChange={(event) => {
            setRole(event.target.value);
            push({ role: event.target.value });
          }}
        >
          {ROLES.map((option) => (
            <option key={option.value} value={option.value}>
              {option.label}
            </option>
          ))}
        </Select>
      </Field>

      <Field label="Status" htmlFor="user-status" className="sm:w-44">
        <Select
          id="user-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>

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