"use client";

import { useRouter, useSearchParams, usePathname } from "next/navigation";
import { useCallback } from "react";

export interface FilterDef {
  key: string;
  label: string;
  type: "search" | "select" | "date";
  options?: { label: string; value: string }[];
}

export function AdminFilterBar({
  filters,
  sortKey = "sort",
}: {
  filters: FilterDef[];
  sortKey?: string;
}) {
  const router = useRouter();
  const pathname = usePathname();
  const params = useSearchParams();

  const update = useCallback(
    (key: string, value: string | null) => {
      const next = new URLSearchParams(params.toString());
      if (value === null || value === "" || value === "all") {
        next.delete(key);
      } else {
        next.set(key, value);
      }
      next.delete("page");
      router.replace(`${pathname}?${next.toString()}`);
    },
    [params, pathname, router],
  );

  const clear = () => router.replace(pathname);

  const active = filters.some((f) => params.get(f.key)) || params.get(sortKey);

  return (
    <div className="flex flex-col gap-2 sm:flex-row sm:flex-wrap sm:items-end">
      {filters.map((f) => {
        const value = params.get(f.key) ?? "";
        if (f.type === "search") {
          return (
            <div key={f.key} className="flex-1 min-w-[180px]">
              <label className="mb-1 block text-xs font-medium text-muted">
                {f.label}
              </label>
              <input
                type="search"
                value={value}
                onChange={(e) => update(f.key, e.target.value)}
                placeholder={f.label}
                className="w-full rounded-lg border border-border bg-surface px-3 py-2 text-sm focus:border-primary focus:outline-none"
              />
            </div>
          );
        }
        if (f.type === "select") {
          return (
            <div key={f.key} className="min-w-[140px]">
              <label className="mb-1 block text-xs font-medium text-muted">
                {f.label}
              </label>
              <select
                value={value}
                onChange={(e) => update(f.key, e.target.value)}
                className="w-full rounded-lg border border-border bg-surface px-3 py-2 text-sm focus:border-primary focus:outline-none"
              >
                <option value="all">{f.label}</option>
                {(f.options ?? []).map((opt) => (
                  <option key={opt.value} value={opt.value}>
                    {opt.label}
                  </option>
                ))}
              </select>
            </div>
          );
        }
        if (f.type === "date") {
          return (
            <div key={f.key} className="min-w-[150px]">
              <label className="mb-1 block text-xs font-medium text-muted">
                {f.label}
              </label>
              <input
                type="date"
                value={value}
                onChange={(e) => update(f.key, e.target.value)}
                className="w-full rounded-lg border border-border bg-surface px-3 py-2 text-sm focus:border-primary focus:outline-none"
              />
            </div>
          );
        }
        return null;
      })}
      {active ? (
        <button
          type="button"
          onClick={clear}
          className="self-end rounded-lg border border-border bg-surface px-3 py-2 text-xs font-medium text-foreground hover:bg-surface-muted"
        >
          Clear filters
        </button>
      ) : null}
    </div>
  );
}

export function AdminSort({
  options,
  sortKey = "sort",
}: {
  options: { label: string; value: string }[];
  sortKey?: string;
}) {
  const router = useRouter();
  const pathname = usePathname();
  const params = useSearchParams();
  const value = params.get(sortKey) ?? "";
  const onChange = (v: string) => {
    const next = new URLSearchParams(params.toString());
    if (!v) next.delete(sortKey);
    else next.set(sortKey, v);
    next.delete("page");
    router.replace(`${pathname}?${next.toString()}`);
  };
  return (
    <div className="flex items-center gap-2">
      <label className="text-xs font-medium text-muted">Sort</label>
      <select
        value={value}
        onChange={(e) => onChange(e.target.value)}
        className="rounded-lg border border-border bg-surface px-3 py-2 text-sm focus:border-primary focus:outline-none"
      >
        <option value="">Default</option>
        {options.map((o) => (
          <option key={o.value} value={o.value}>
            {o.label}
          </option>
        ))}
      </select>
    </div>
  );
}