"use client";

import * as React from "react";
import { XIcon, type LucideIcon } from "lucide-react";

import { cn } from "@/lib/utils";

/* ------------------------------------- Label tag ------------------------------------- */

/**
 * Label tag (spec 02 §3): a descriptive attribute of a record, not a state ("Rx", "Service", "Company").
 * Not interactive. `accent` (lime) is for "New" or "Featured" only, one or two per screen.
 */
export function LabelTag({ children, icon: Icon, accent = false, size = "compact", className }: { children: React.ReactNode; icon?: LucideIcon; accent?: boolean; size?: "compact" | "comfortable"; className?: string }) {
  return (
    <span
      className={cn(
        "inline-flex items-center gap-1 rounded-full px-2 text-xs font-medium whitespace-nowrap",
        size === "compact" ? "h-5" : "h-6",
        accent
          ? "bg-[var(--color-bg-accent)] text-[var(--color-fg-on-accent)]"
          : "border border-[var(--color-border-panel)] bg-[var(--color-bg-surface-subtle)] text-[var(--color-fg-secondary-strong)]",
        className,
      )}
    >
      {Icon ? <Icon className="size-3.5" aria-hidden /> : null}
      {children}
    </span>
  );
}

/* ------------------------------------ Filter chips ----------------------------------- */

export type AppliedFilter = { key: string; field: string; value: string };

/**
 * Applied filters (spec 02 §3) as removable chips, with Clear all when two or more are applied. Only the
 * remove buttons take focus. Removing moves focus to the next chip's button, or to `returnFocusTo` (the
 * Filters control) when none remain. Backspace or Delete on a remove button also removes. `announce` is
 * the polite message after a change, e.g. "Showing 1,284 sales".
 */
export function FilterChips({
  filters,
  onRemove,
  onClearAll,
  returnFocusTo,
  announce,
  density = "compact",
}: {
  filters: AppliedFilter[];
  onRemove: (key: string) => void;
  onClearAll: () => void;
  returnFocusTo?: React.RefObject<HTMLElement | null>;
  announce?: string;
  density?: "compact" | "comfortable";
}) {
  const listRef = React.useRef<HTMLUListElement>(null);
  const [message, setMessage] = React.useState("");

  const focusAfter = (index: number) => {
    // After React re-renders: the chip now at `index` (the next one), else the previous, else the Filters control.
    setTimeout(() => {
      const buttons = listRef.current?.querySelectorAll<HTMLButtonElement>("button[data-remove]") ?? [];
      const target = buttons[index] ?? buttons[index - 1];
      if (target) target.focus();
      else returnFocusTo?.current?.focus();
    }, 0);
  };

  const remove = (f: AppliedFilter, index: number) => {
    onRemove(f.key);
    setMessage(`Filter removed: ${f.field} ${f.value}.`);
    focusAfter(index);
  };

  if (!filters.length) {
    return (
      <p className="sr-only" aria-live="polite">
        {message ? `${message} ${announce ?? ""}` : ""}
      </p>
    );
  }

  return (
    <div className={cn("flex flex-wrap items-center", density === "compact" ? "gap-1.5" : "gap-2")}>
      <ul ref={listRef} aria-label="Applied filters" className={cn("flex flex-wrap items-center", density === "compact" ? "gap-1.5" : "gap-2")}>
        {filters.map((f, i) => (
          <li
            key={f.key}
            className={cn(
              "inline-flex items-center gap-0.5 rounded-sm border border-[var(--color-border-strong)] bg-[var(--color-bg-selected)] pr-0.5 pl-2 text-[13px] leading-[18px] font-medium text-foreground",
              density === "compact" ? "h-6" : "h-8",
            )}
          >
            <span>
              {f.field}: <span className="font-semibold">{f.value}</span>
            </span>
            <button
              type="button"
              data-remove
              aria-label={`Remove filter: ${f.field} ${f.value}`}
              onClick={() => remove(f, i)}
              onKeyDown={(e) => {
                if (e.key === "Backspace" || e.key === "Delete") {
                  e.preventDefault();
                  remove(f, i);
                }
              }}
              className="flex size-6 cursor-pointer items-center justify-center rounded-full text-muted-foreground outline-none hover:bg-[var(--color-bg-hover)] hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
            >
              <XIcon className="size-3.5" aria-hidden />
            </button>
          </li>
        ))}
      </ul>
      {filters.length >= 2 ? (
        <button
          type="button"
          onClick={() => {
            onClearAll();
            setMessage("All filters removed.");
            setTimeout(() => returnFocusTo?.current?.focus(), 0);
          }}
          className="cursor-pointer rounded-sm px-1 text-[13px] font-medium text-primary underline-offset-2 outline-none hover:underline focus-visible:ring-2 focus-visible:ring-ring"
        >
          Clear all
        </button>
      ) : null}
      <p className="sr-only" aria-live="polite">
        {message ? `${message} ${announce ?? ""}` : ""}
      </p>
    </div>
  );
}
