"use client";

import { useTranslation } from "@enode/core/translations/hooks";
import { DataEmptyState } from "@enode/ui/feedback/data-empty-state";
import { Button } from "@enode/ui/button";
import { MagnifyingGlassIcon } from "@enode/ui/icons";

// The empty view a search / filter leaves behind when nothing matches — shared
// by every list and table page in the portal (Users, Exercises, Workouts, Tags,
// Devices) and by the tracking app's searchable drawers. It's
// deliberately a sibling of the first-run TableEmptyState, not the same thing:
// that one sells an empty *collection* (ghost-table backdrop, feature CTA); this
// one handles a *narrowed-to-nothing* view. So it drops the ghost table and uses
// a muted search glyph instead of a platinum feature tile — same empty-state
// vocabulary, but clearly "your query, not your account, is empty".
//
// Beyond a dead-end message it does two things: names the query and offers to
// clear it / the filters, and — when the page can find near-matches still in
// scope — shows "Did you mean" chips that re-run the search on a real item.

/** A near-match the empty view offers as a one-tap correction. */
export type NoResultsSuggestion = {
  /** Stable React key (usually the item id). */
  key: string;
  /** The already-localized label shown on the chip. */
  label: string;
  /** Re-run the search on this suggestion (typically `setQuery(label)`). */
  onSelect: () => void;
};

export function NoResults({
  query,
  otherFiltersActive = false,
  suggestions = [],
  onClearSearch,
  onClearFilters,
  title,
  description,
  className,
}: {
  /** The current search text (drives the headline + which actions show). */
  query: string;
  /** Whether non-search filters (tags, roles, facets…) are also narrowing. */
  otherFiltersActive?: boolean;
  /** Near-matches still in scope, best first (see `suggestAlternatives`). */
  suggestions?: NoResultsSuggestion[];
  /** Clear only the search text. Shown while `query` is non-empty. */
  onClearSearch?: () => void;
  /** Clear every filter (and the search). Shown while a filter is active. */
  onClearFilters?: () => void;
  /** Override the default headline. */
  title?: string;
  /** Override the default guidance line. */
  description?: string;
  className?: string;
}) {
  const { t } = useTranslation();
  const trimmed = query.trim();
  const hasQuery = trimmed !== "";

  const resolvedTitle =
    title ??
    (hasQuery
      ? t("No results for “{query}”", { query: trimmed })
      : t("No matching results"));

  const resolvedDescription =
    description ??
    (hasQuery && otherFiltersActive
      ? t("Try a different search term, or remove some filters to widen it.")
      : hasQuery
        ? t("Check for typos, or try a shorter or different search term.")
        : t("Try removing some filters to see more results."));

  return (
    <DataEmptyState
      className={className}
      icon={
        <span className="flex size-14 items-center justify-center rounded-2xl bg-surface-base-muted text-foreground-muted">
          <MagnifyingGlassIcon className="size-7" />
        </span>
      }
      title={resolvedTitle}
      description={resolvedDescription}
      action={
        hasQuery && onClearSearch ? (
          <Button variant="neutral" size="rounded" onClick={onClearSearch}>
            {t("Clear search")}
          </Button>
        ) : undefined
      }
      secondaryAction={
        otherFiltersActive && onClearFilters ? (
          <Button variant="neutral" size="rounded" onClick={onClearFilters}>
            {t("Clear filters")}
          </Button>
        ) : undefined
      }
    >
      {suggestions.length > 0 && (
        <div className="flex flex-col items-center gap-2">
          <span className="stat-small uppercase text-foreground-more-muted">
            {t("Did you mean")}
          </span>
          <div className="flex flex-wrap items-center justify-center gap-2">
            {suggestions.map((s) => (
              <button
                key={s.key}
                type="button"
                onClick={s.onSelect}
                className="body-prominent rounded-full border border-surface-stroke bg-surface-base px-3.5 py-1.5 text-foreground-default transition-colors hover:border-foreground-platinum-green hover:text-foreground-platinum-green"
              >
                {s.label}
              </button>
            ))}
          </div>
        </div>
      )}
    </DataEmptyState>
  );
}
