"use client";

import * as React from "react";
import { usePathname, useRouter } from "next/navigation";
import { FilterX } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Field, Select } from "@/components/ui/input";
import type { AuditFacet } from "@/lib/queries/admin";

/**
 * Audit trail filters.
 *
 * The action/entity/actor option lists come from the database (`getAuditFacets`)
 * so the selects can only ever offer values that exist. State lives in the URL
 * and the server component re-queries on every change.
 */
export function AuditFilters({
  actions,
  entities,
  actors,
  initial,
}: {
  actions: AuditFacet[];
  entities: AuditFacet[];
  actors: { id: string; name: string; username: string }[];
  initial: { actorId: string; action: string; entity: string };
}) {
  const router = useRouter();
  const pathname = usePathname();
  const [action, setAction] = React.useState(initial.action);
  const [actorId, setActorId] = React.useState(initial.actorId);
  const [entity, setEntity] = React.useState(initial.entity);

  function push(next: { action?: string; actorId?: string; entity?: string }) {
    const params = new URLSearchParams();
    const nextAction = next.action ?? action;
    const nextActor = next.actorId ?? actorId;
    const nextEntity = next.entity ?? entity;
    if (nextAction) params.set("action", nextAction);
    if (nextActor) params.set("actorId", nextActor);
    if (nextEntity) params.set("entity", nextEntity);
    const query = params.toString();
    router.replace(query ? `${pathname}?${query}` : pathname, { scroll: false });
  }

  const hasFilters = Boolean(action || actorId || entity);

  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="Aksi" htmlFor="audit-action" className="lg:flex-1">
        <Select
          id="audit-action"
          value={action}
          onChange={(event) => {
            setAction(event.target.value);
            push({ action: event.target.value });
          }}
        >
          <option value="">Semua aksi</option>
          {actions.map((facet) => (
            <option key={facet.value} value={facet.value}>
              {facet.value} ({facet.count})
            </option>
          ))}
        </Select>
      </Field>

      <Field label="Entitas" htmlFor="audit-entity" className="lg:w-48">
        <Select
          id="audit-entity"
          value={entity}
          onChange={(event) => {
            setEntity(event.target.value);
            push({ entity: event.target.value });
          }}
        >
          <option value="">Semua entitas</option>
          {entities.map((facet) => (
            <option key={facet.value} value={facet.value}>
              {facet.value} ({facet.count})
            </option>
          ))}
        </Select>
      </Field>

      <Field label="Pelaku" htmlFor="audit-actor" className="lg:w-56">
        <Select
          id="audit-actor"
          value={actorId}
          onChange={(event) => {
            setActorId(event.target.value);
            push({ actorId: event.target.value });
          }}
        >
          <option value="">Semua pelaku</option>
          {actors.map((actor) => (
            <option key={actor.id} value={actor.id}>
              {actor.name} (@{actor.username})
            </option>
          ))}
        </Select>
      </Field>

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