"use client";

import { useRef, useState, type ReactNode } from "react";
import type { EntityTagReturnDto } from "@enode/core/api/dtos/tags";
import type { TagMatch } from "@enode/core/tags/filter-match";
import { tagDotStyle, tagPillStyle } from "@enode/core/tags/tag-style";
import { displayName } from "@enode/core/text-content/display-name";
import { useDisplayName } from "@enode/core/text-content/useDisplayName";
import { useTranslation } from "@enode/core/translations/hooks";
import { useMediaQuery } from "@enode/core/use-media-query";
import { BottomSheetCard } from "./bottom-sheet-card";
import { PHONE_QUERY } from "./choice-menu";
import { ContainmentProvider } from "./containment";
import { CloseXIcon } from "./icons/close-x";
import { Line3HorizontalDecreaseIcon } from "./icons";
import { SegmentedPicker } from "./segmented-picker";
import { popoverZIndex, useSurfaceZIndex } from "./surface-z-index";
import { TAP_TARGET } from "./tap-target";
import {
  MenuCheckRow,
  MenuEmptyRow,
  MenuExpandRow,
  MenuPanelAction,
  MenuPanelHeader,
  MenuPanelSection,
  MenuPopover,
  MenuSearchField,
} from "./menu-panel";

// The search bar of every list page and searchable drawer — the portal's one
// filter-bar pattern (docs/components.md, "Search and filter bars"). At rest it
// is ONE row: the search field, the host's query controls (`actions`, e.g. the
// inline date range), and one "Filters" control. Everything that is applied
// shows in a second strip under the input — tags in their colours, everything
// else neutral — with a single "Clear filters". Nothing else is permanent.
//
// The "Filters" control (present whenever there are facets or tags) opens the
// "Filters" menu — the shared settings popover of `./menu-panel` (the tables'
// "Columns" menu), a bottom sheet on phones: one section per facet group with a
// check row per option, then "Tags" — the suggested and applied tags with their
// colour dots, expanding in place to every tag on offer (with a search field
// for long lists) — and "Clear" in the title row. Tags never open a second
// surface. With neither facets nor tags the card is a plain search field.
//
// `tagMatch` + `onTagMatchChange` opt in to an "Any tag / All tags" switch in
// the strip, shown once two or more tags are active. The caller applies the
// match to its list (see `matchesTagFilter`).
//
// `appliedFilters` lets a host whose applied filters are neither tags of
// `tags` nor facet options (History's athlete / exercise tokens) show them in
// the same strip; `onClearFilters` owns what "Clear filters" resets.
//
// The caller owns the search, tag and facet state; this component is
// presentational + UX.
const NO_TAGS: ReadonlyArray<EntityTagReturnDto> = [];
const NO_TAG_IDS: ReadonlySet<string> = new Set();
const NO_APPLIED: ReadonlyArray<ReactNode> = [];
const NO_GROUPS: ReadonlyArray<FilterGroup> = [];

/** One option of a facet group in the "Filters" menu. */
export type FilterOption = {
  /** Unique within its group. */
  id: string;
  /** Already-localized name, shown on the chip in the menu and in the strip. */
  label: string;
  active: boolean;
  onToggle: () => void;
};

/** A facet group of the "Filters" menu (roles, tracking source, …). */
export type FilterGroup = {
  key: string;
  /** Already-localized heading over the group's chips in the menu. */
  label: string;
  /** An empty group is not shown. */
  options: ReadonlyArray<FilterOption>;
};

export function SearchAndFilterCard({
  search,
  onSearch,
  tags = NO_TAGS,
  activeTagIDs = NO_TAG_IDS,
  onTagToggle,
  placeholder,
  actions,
  filterGroups = NO_GROUPS,
  suggestedTags = NO_TAGS,
  tagMatch = "any",
  onTagMatchChange,
  appliedFilters = NO_APPLIED,
  onClearFilters,
  className = "",
  autoFocus = false,
}: {
  search: string;
  onSearch: (v: string) => void;
  /** Tags to filter by: every tag the menu's Tags section can offer. */
  tags?: ReadonlyArray<EntityTagReturnDto>;
  activeTagIDs?: ReadonlySet<string>;
  onTagToggle?: (id: string) => void;
  placeholder?: string;
  /**
   * Query controls for the search row, before "Filters" — the inline
   * `DateRangePicker`. Not for facets: those go in `filterGroups`.
   */
  actions?: ReactNode;
  /** Facet groups of the "Filters" menu; their active options show in the strip. */
  filterGroups?: ReadonlyArray<FilterGroup>;
  /** One-tap tags at the top of the menu's "Tags" section (e.g. most used). */
  suggestedTags?: ReadonlyArray<EntityTagReturnDto>;
  /** How the active tag filters combine; shown only with `onTagMatchChange`. */
  tagMatch?: TagMatch;
  /** Renders the "Any tag / All tags" switch while ≥ 2 tags are active. */
  onTagMatchChange?: (match: TagMatch) => void;
  /**
   * Applied filters that are neither tags nor facet options (keyed nodes,
   * usually `AppliedFilterChip`s), shown first in the strip.
   */
  appliedFilters?: ReadonlyArray<ReactNode>;
  /**
   * What "Clear filters" in the strip does. Defaults to toggling every active
   * tag and facet option off; pass it when the strip also shows
   * `appliedFilters`, or when the host can't apply several toggles in a row.
   */
  onClearFilters?: () => void;
  className?: string;
  /** Focus the field on mount (e.g. the first step of a flow on desktop). */
  autoFocus?: boolean;
}) {
  const { t } = useTranslation();
  const triggerRef = useRef<HTMLButtonElement>(null);
  const [menuOpen, setMenuOpen] = useState(false);
  // Bumped on every opening: the menu body remounts, so "Show all tags" and the
  // tag search start fresh (the phone sheet stays mounted while it animates).
  const [menuSession, setMenuSession] = useState(0);
  function toggleMenu() {
    if (!menuOpen) setMenuSession((n) => n + 1);
    setMenuOpen(!menuOpen);
  }
  const phone = useMediaQuery(PHONE_QUERY);
  // Over whatever hosts the card (a nested drawer climbs above the default).
  const surfaceZ = useSurfaceZIndex();

  const selectedTags = tags.filter((tag) => activeTagIDs.has(tag.id));

  const groups = filterGroups.filter((group) => group.options.length > 0);
  const activeOptions = groups.flatMap((group) =>
    group.options.filter((option) => option.active),
  );
  const hasMenu = groups.length > 0 || tags.length > 0 || suggestedTags.length > 0;
  const activeCount = activeOptions.length + selectedTags.length;

  function clearFilters() {
    if (onClearFilters) {
      onClearFilters();
      return;
    }
    // Callers own their sets via functional updates, so N toggles batch cleanly.
    for (const id of activeTagIDs) onTagToggle?.(id);
    for (const option of activeOptions) option.onToggle();
  }
  const hasAppliedFilters =
    appliedFilters.length > 0 || activeOptions.length > 0 || selectedTags.length > 0;
  // The Tags section's first rows: the suggestions, then any other applied
  // tag, so every applied tag can be unticked where it was picked.
  const suggestedIDs = new Set(suggestedTags.map((tag) => tag.id));
  const pinnedTags = [
    ...suggestedTags,
    ...selectedTags.filter((tag) => !suggestedIDs.has(tag.id)),
  ];

  // One body for both surfaces: the anchored panel on desktop and tablets,
  // the bottom sheet on phones — same rows either way.
  const filterMenuBody = (
    <FilterMenuBody
      key={menuSession}
      groups={groups}
      pinnedTags={pinnedTags}
      allTags={tags}
      activeTagIDs={activeTagIDs}
      onTagToggle={(id) => onTagToggle?.(id)}
      onClear={hasAppliedFilters ? clearFilters : undefined}
    />
  );
  const filterMenu = !hasMenu ? null : phone ? (
    // The whole screen: the card may sit in a box that would otherwise frame
    // the sheet (see ChoiceMenu).
    <ContainmentProvider value="viewport">
      <BottomSheetCard
        open={menuOpen}
        onClose={() => setMenuOpen(false)}
        ariaLabel={t("Filters")}
        zIndex={popoverZIndex(surfaceZ)}
      >
        {/* Long lists scroll inside the sheet under the sticky title row. */}
        <div className="max-h-[75dvh] overflow-y-auto overscroll-contain rounded-t-[28px] bg-inherit px-4 pt-3">
          {filterMenuBody}
        </div>
      </BottomSheetCard>
    </ContainmentProvider>
  ) : (
    <MenuPopover
      open={menuOpen}
      onClose={() => setMenuOpen(false)}
      triggerRef={triggerRef}
      label={t("Filters")}
    >
      {filterMenuBody}
    </MenuPopover>
  );

  return (
    <div
      className={`overflow-hidden rounded-2xl border border-surface-stroke bg-surface-base ${className}`}
    >
      <label className="flex items-center gap-2 px-4 py-2.5">
        <SearchIcon className="size-4 shrink-0 text-foreground-muted" />
        <input
          type="text"
          autoFocus={autoFocus}
          value={search}
          onChange={(e) => onSearch(e.target.value)}
          placeholder={placeholder ?? t("Search")}
          // A placeholder is not a name: a screen reader gets the same words
          // as the field's label.
          aria-label={placeholder ?? t("Search")}
          className="body-normal w-full bg-transparent text-foreground-default outline-none placeholder:text-foreground-muted"
        />
        {search && (
          <button
            type="button"
            onClick={() => onSearch("")}
            aria-label={t("Clear search")}
            className={`${TAP_TARGET} flex size-5 items-center justify-center rounded-full text-foreground-muted hover:text-foreground-default`}
          >
            <XIcon className="size-3.5" />
          </button>
        )}
        {actions}
        {hasMenu && (
          <>
            <FilterDivider />
            <button
              ref={triggerRef}
              type="button"
              onClick={toggleMenu}
              aria-haspopup="dialog"
              aria-expanded={menuOpen}
              aria-label={
                activeCount > 0
                  ? t("Filters, {count} applied", { count: activeCount })
                  : t("Filters")
              }
              // 44 px tap target on phones, where it is icon-only; the
              // negative margin keeps the visual size of the row.
              className={`${FILTER_TRIGGER} ${activeCount > 0 ? "text-foreground-default" : ""}`}
            >
              <Line3HorizontalDecreaseIcon className="size-4 shrink-0" />
              {/* Compact screens: icon-only (the aria-label carries the name). */}
              <span className="hidden sm:inline">{t("Filters")}</span>
              {activeCount > 0 && (
                <span
                  aria-hidden
                  className="stat-small flex h-4 min-w-4 items-center justify-center rounded-full bg-foreground-default px-1 tabular-nums text-surface-base"
                >
                  {activeCount}
                </span>
              )}
            </button>
          </>
        )}
      </label>

      {/* Applied filters: removable chips + one clear-all. Only rendered while
          a filter is applied, so the card stays a single row otherwise. */}
      {hasAppliedFilters && (
        <>
          <div className="border-t border-surface-stroke" />
          <div className="flex flex-wrap items-center gap-1.5 px-4 py-2.5">
            {onTagMatchChange && selectedTags.length >= 2 && (
              <div className="mr-1 flex shrink-0 items-center gap-2">
                <span className="body-small text-foreground-muted">
                  {t("Match")}
                </span>
                <SegmentedPicker<TagMatch>
                  value={tagMatch}
                  onChange={onTagMatchChange}
                  ariaLabel={t("How tag filters combine")}
                  options={[
                    { value: "any", label: t("Any tag") },
                    { value: "all", label: t("All tags") },
                  ]}
                />
              </div>
            )}
            {appliedFilters}
            {groups.flatMap((group) =>
              group.options
                .filter((option) => option.active)
                .map((option) => (
                  <AppliedFilterChip
                    key={`${group.key}:${option.id}`}
                    label={option.label}
                    onRemove={option.onToggle}
                  />
                )),
            )}
            {selectedTags.map((tag) => (
              <SelectedTagChip
                key={tag.id}
                tag={tag}
                onRemove={() => onTagToggle?.(tag.id)}
              />
            ))}
            <ClearFiltersButton onClick={clearFilters} />
          </div>
        </>
      )}

      {filterMenu}
    </div>
  );
}

// More tags than this, and the expanded Tags section gets its search field.
const TAG_SEARCH_MIN = 6;

// The "Filters" menu, in the shared settings-popover vocabulary (the tables'
// "Columns" menu, `./menu-panel`): a sticky title row with "Clear" while
// something is applied, one section per facet group, then "Tags". Tags stay in
// this menu: first the pinned rows (suggested + applied); "Show all tags"
// expands the section in place to every tag on offer, with a search field once
// there are more than a handful. With nothing pinned the full list shows
// straight away.
function FilterMenuBody({
  groups,
  pinnedTags,
  allTags,
  activeTagIDs,
  onTagToggle,
  onClear,
}: {
  groups: ReadonlyArray<FilterGroup>;
  pinnedTags: ReadonlyArray<EntityTagReturnDto>;
  allTags: ReadonlyArray<EntityTagReturnDto>;
  activeTagIDs: ReadonlySet<string>;
  onTagToggle: (id: string) => void;
  /** Shown as "Clear" only while something is applied. */
  onClear?: () => void;
}) {
  const { t } = useTranslation();
  const [showAll, setShowAll] = useState(false);
  const [tagQuery, setTagQuery] = useState("");

  const pinnedIDs = new Set(pinnedTags.map((tag) => tag.id));
  const expanded = showAll || pinnedTags.length === 0;
  // Expanded: the pinned rows keep their place on top, the rest follow by
  // name, so nothing the coach just saw jumps.
  const rest = allTags
    .filter((tag) => !pinnedIDs.has(tag.id))
    .sort((a, b) => displayName(a).localeCompare(displayName(b)));
  const listed = expanded ? [...pinnedTags, ...rest] : pinnedTags;
  const searchable = expanded && listed.length > TAG_SEARCH_MIN;
  const term = searchable ? tagQuery.trim().toLowerCase() : "";
  const shown = term
    ? listed.filter((tag) => displayName(tag).toLowerCase().includes(term))
    : listed;
  const canExpand = !expanded && rest.length > 0;

  return (
    <>
      <MenuPanelHeader
        sticky
        title={t("Filters")}
        action={
          onClear ? (
            <MenuPanelAction onClick={onClear}>{t("Clear")}</MenuPanelAction>
          ) : undefined
        }
      />
      {groups.map((group) => (
        <MenuPanelSection key={group.key} label={group.label}>
          {group.options.map((option) => (
            <MenuCheckRow
              key={option.id}
              label={option.label}
              checked={option.active}
              onToggle={option.onToggle}
            />
          ))}
        </MenuPanelSection>
      ))}
      {listed.length > 0 && (
        <MenuPanelSection label={t("Tags")}>
          {searchable && (
            <MenuSearchField
              value={tagQuery}
              onChange={setTagQuery}
              label={t("Search tags…")}
            />
          )}
          {shown.map((tag) => (
            <TagCheckRow
              key={tag.id}
              tag={tag}
              checked={activeTagIDs.has(tag.id)}
              onToggle={() => onTagToggle(tag.id)}
            />
          ))}
          {term && shown.length === 0 && (
            <MenuEmptyRow>{t("No tag matches.")}</MenuEmptyRow>
          )}
          {canExpand && (
            <MenuExpandRow
              label={t("Show all tags ({count})", {
                count: pinnedTags.length + rest.length,
              })}
              onClick={() => setShowAll(true)}
            />
          )}
        </MenuPanelSection>
      )}
    </>
  );
}

// A tag as a menu row: its colour dot, its localized name, the check.
function TagCheckRow({
  tag,
  checked,
  onToggle,
}: {
  tag: EntityTagReturnDto;
  checked: boolean;
  onToggle: () => void;
}) {
  const label = useDisplayName(tag, "—");
  return (
    <MenuCheckRow
      label={label}
      checked={checked}
      onToggle={onToggle}
      leading={
        <span
          aria-hidden
          className="size-2.5 shrink-0 rounded-full border"
          style={tagDotStyle(tag.colorCode)}
        />
      }
    />
  );
}

/**
 * One applied tag filter: the TagPill look (tag colour, size, casing, width
 * cap) with a trailing ✕. Clicking anywhere on the chip removes the filter.
 * Also used by filter bars outside this card (the planner's athlete/tag
 * filter).
 */
export function SelectedTagChip({
  tag,
  onRemove,
}: {
  tag: EntityTagReturnDto;
  onRemove: () => void;
}) {
  const { t } = useTranslation();
  // Localized tag name (System A): literal name, else resolved nameTextContentID.
  const label = useDisplayName(tag, "—");
  return (
    <button
      type="button"
      onClick={onRemove}
      aria-label={t("Remove {name} filter", { name: label })}
      title={label}
      className="stat-small inline-flex min-w-0 max-w-[200px] shrink-0 items-center gap-1 rounded-full border px-2.5 py-1 capitalize"
      style={tagPillStyle(tag.colorCode)}
    >
      <span className="cap-trim -my-1 min-w-0 truncate py-1">{label}</span>
      <XIcon className="size-3 shrink-0" />
    </button>
  );
}

/**
 * One applied filter that is not a tag (an athlete, an exercise, …): the
 * neutral counterpart of `SelectedTagChip`, same shape, with an optional
 * muted kind prefix ("Athlete:"). Clicking it removes the filter.
 *
 * @param kind - already-localized prefix naming what the value is.
 * @param label - the filter value as shown (an entity name, not translated).
 */
export function AppliedFilterChip({
  kind,
  label,
  onRemove,
}: {
  kind?: string;
  label: string;
  onRemove: () => void;
}) {
  const { t } = useTranslation();
  return (
    <button
      type="button"
      onClick={onRemove}
      aria-label={t("Remove {name} filter", { name: label })}
      title={kind ? `${kind}: ${label}` : label}
      className="stat-small inline-flex min-w-0 max-w-[240px] shrink-0 items-center gap-1 rounded-full border border-surface-stroke bg-surface-base-muted px-2.5 py-1 text-foreground-default"
    >
      <span className="cap-trim -my-1 min-w-0 truncate py-1">
        {kind ? <span className="text-foreground-muted">{kind}: </span> : null}
        {label}
      </span>
      <XIcon className="size-3 shrink-0 text-foreground-muted" />
    </button>
  );
}

/**
 * The trigger chrome for controls inside the search row (the "Filters"
 * button, the inline `DateRangePicker`): borderless, muted, icon first, a
 * 44 px tap target on phones where it shows the icon only.
 */
export const FILTER_TRIGGER =
  "clickable-small -my-3 flex min-h-11 min-w-11 shrink-0 items-center justify-center gap-1.5 whitespace-nowrap text-foreground-muted transition-colors hover:text-foreground-default sm:min-w-0";

/** The 1 px rule between the controls of the search row. */
export function FilterDivider() {
  return <span aria-hidden className="h-5 w-px shrink-0 bg-surface-stroke" />;
}

/**
 * "Clear filters", the same look wherever a filter bar offers it: the last item
 * of the applied-filters strip (or of a page's own filter row), pushed to the
 * end. Render it only while something is filtered.
 */
export function ClearFiltersButton({ onClick }: { onClick: () => void }) {
  const { t } = useTranslation();
  return (
    <button
      type="button"
      onClick={onClick}
      className={`${TAP_TARGET} clickable-small ml-auto shrink-0 whitespace-nowrap text-foreground-muted transition-colors hover:text-foreground-default`}
    >
      {t("Clear filters")}
    </button>
  );
}

// ─── Local icons ────────────────────────────────────────────────────────────
// Kept inline so the shared card doesn't take a dependency on the route's
// icon module — `src/lib/ui/` shouldn't reach back into `src/app/`.

type IconProps = { className?: string };

function SearchIcon({ className }: IconProps) {
  return (
    <svg
      xmlns="http://www.w3.org/2000/svg"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth={2}
      className={className}
      aria-hidden="true"
    >
      <path
        strokeLinecap="round"
        strokeLinejoin="round"
        d="m21 21-5.197-5.197m0 0A7.5 7.5 0 1 0 5.196 5.196a7.5 7.5 0 0 0 10.607 10.607Z"
      />
    </svg>
  );
}

function XIcon({ className }: IconProps) {
  return <CloseXIcon className={className} />;
}
