"use client";

import { useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { CustomSelect } from "../../../components/CustomSelect";

// Three custom-styled dropdowns in a row instead of a wall of filter
// chips (tried first, reverted 2026-07-30 — with 7 status options + 5
// payment-status options + N years, a chip per option read as cluttered
// and ate a lot of vertical space) or plain native <select>s (tried next,
// also reverted the same day — a native <select>'s open options popup is
// rendered by the browser/OS and can't be styled at all, so it looked
// completely off-brand next to everything else on the page; see
// CustomSelect.tsx for the fully custom-styled replacement). Client
// Component only for the onChange→navigate wiring; the actual filtering
// still happens server-side in page.tsx via the same URL search params,
// so this stays a plain GET-style filter (shareable/bookmarkable/
// back-button-safe), not client-side state.
export function OrderFilters({
  statusOptions,
  paymentStatusOptions,
  years,
}: {
  statusOptions: { value: string; label: string }[];
  paymentStatusOptions: { value: string; label: string }[];
  years: string[];
}) {
  const router = useRouter();
  const searchParams = useSearchParams();

  const status = searchParams.get("status") ?? "";
  const paymentStatus = searchParams.get("paymentStatus") ?? "";
  const year = searchParams.get("year") ?? "";
  const hasAnyFilter = Boolean(status || paymentStatus || year);
  const activeCount = [status, paymentStatus, year].filter(Boolean).length;

  // Collapsed by default on mobile — with the account tab bar now also
  // stacked above this (see KontoShell/AccountNav), 3 full-width dropdowns
  // always visible left little room for the actual order list. Desktop
  // (sm+) ignores this entirely and always shows the row inline, same as
  // before. Starts expanded whenever a filter is already active (arriving
  // via a shared/bookmarked filtered URL shouldn't hide what's applied) —
  // a lazy initializer since it only needs to run once, on mount.
  const [expanded, setExpanded] = useState(() => hasAnyFilter);

  function setParam(key: string, value: string) {
    const params = new URLSearchParams(searchParams.toString());
    if (value) params.set(key, value);
    else params.delete(key);
    const qs = params.toString();
    router.push(qs ? `/konto/bestellungen?${qs}` : "/konto/bestellungen");
  }

  const yearOptions = years.map((y) => ({ value: y, label: y }));

  return (
    <div className="w-full">
      <button
        type="button"
        onClick={() => setExpanded((v) => !v)}
        className="sm:hidden flex items-center justify-between w-full px-4 py-3 border border-border rounded-sm text-body-sm font-bold text-text-primary"
      >
        <span className="flex items-center gap-2">
          Filter
          {activeCount > 0 && (
            <span className="flex items-center justify-center min-w-[1.1rem] h-[1.1rem] px-1 rounded-full bg-brand text-[0.6875rem] font-bold leading-none text-text-primary">
              {activeCount}
            </span>
          )}
        </span>
        <span aria-hidden>{expanded ? "▴" : "▾"}</span>
      </button>
      <div
        className={`${expanded ? "flex" : "hidden"} sm:flex flex-col sm:flex-row sm:items-center gap-3 w-full mt-3 sm:mt-0`}
      >
        <CustomSelect label="Alle Status" options={statusOptions} value={status} onChange={(v) => setParam("status", v)} />
        <CustomSelect label="Alle Zahlungsstatus" options={paymentStatusOptions} value={paymentStatus} onChange={(v) => setParam("paymentStatus", v)} />
        <CustomSelect label="Alle Jahre" options={yearOptions} value={year} onChange={(v) => setParam("year", v)} />
        {hasAnyFilter && (
          <button
            type="button"
            onClick={() => router.push("/konto/bestellungen")}
            className="text-body-sm font-semibold text-text-muted underline hover:text-brand transition-colors self-start sm:self-auto"
          >
            Zurücksetzen
          </button>
        )}
      </div>
    </div>
  );
}
