import type { ReactNode } from "react";
import { ArrowUpRightSquareIcon } from "../icons";
import { ChevronRightIcon } from "./icons";

// A settings row in the enode screen look: an optional monochrome icon, a
// label (and an optional sublabel), a grey value and a chevron. Purely
// presentational — all copy comes in via props, so callers own i18n via t().
// Stack rows inside a `SettingsCardGroup` (or a `Card` from
// @enode/ui/list-rows) and separate them with {@link NavRowDivider}.

/** Props of {@link NavRow}. */
export type NavRowProps = {
  /** Leading monochrome glyph (decorative; the label says what it is). */
  icon?: ReactNode;
  label: string;
  /** One quiet line under the label. */
  sublabel?: string;
  /** What the setting is set to, grey on the right; truncates. Hidden on destructive rows. */
  value?: ReactNode;
  /** Makes the row a `<button type="button">`. */
  onPress?: () => void;
  /** Makes the row an `<a>` (wins over `onPress`). */
  href?: string;
  /**
   * Shows an arrow-up-right instead of the chevron (the row leaves the app);
   * with `href` it also opens in a new tab.
   */
  external?: boolean;
  /** Passed through as `aria-description` (e.g. "Opens in a new tab"). */
  ariaDescription?: string;
  /** Label in the error colour, no chevron, no value (e.g. "Delete account"). */
  destructive?: boolean;
  /**
   * Replaces the chevron, e.g. a `<Toggle/>`; use it on a row without `href`/`onPress`.
   * When trailing is an interactive control (e.g. Toggle), give it its own aria-label — the row itself is not a label for it.
   */
  trailing?: ReactNode;
  /** `aria-disabled`, dimmed, and the handler / link is dropped. */
  disabled?: boolean;
  /** Becomes `data-find`: the target the settings search highlights. */
  findId?: string;
  className?: string;
};

/**
 * One settings row, at least 44 px high and full width: an optional
 * icon, the label (and sublabel), an optional grey value and a trailing
 * chevron.
 *
 * @remarks
 * The element follows the props: `href` renders an `<a>`, `onPress` a
 * `<button type="button">`, neither a plain `<div>` (a row whose control is
 * its `trailing`, such as a Toggle). The chevron shows only on rows that
 * navigate; `external` rows (links or buttons) show an arrow-up-right instead, and
 * `destructive` rows show neither. Separate rows with {@link NavRowDivider}.
 */
export function NavRow({
  icon,
  label,
  sublabel,
  value,
  onPress,
  href,
  external,
  ariaDescription,
  destructive,
  trailing,
  disabled,
  findId,
  className = "",
}: NavRowProps) {
  const kind: "a" | "button" | "div" =
    href != null ? "a" : onPress ? "button" : "div";
  const interactive = kind !== "div" && !disabled;

  let end: ReactNode = null;
  if (trailing != null) end = <span className="min-w-0">{trailing}</span>;
  else if (destructive || kind === "div") end = null;
  else if (external)
    end = <ArrowUpRightSquareIcon className="size-4 shrink-0 text-foreground-muted" />;
  else end = <ChevronRightIcon className="size-4 shrink-0 text-foreground-muted" />;

  const hasValue = value != null && !destructive;

  const labelColor = destructive ? "text-feedback-error" : "text-foreground-default";
  const content = (
    <>
      {icon != null && (
        <span
          aria-hidden="true"
          className="flex size-6 shrink-0 items-center justify-center text-foreground-default [&>svg]:size-5"
        >
          {icon}
        </span>
      )}
      <span className={hasValue ? "min-w-0 max-w-[60%] shrink-0" : trailing != null ? "shrink-0" : "min-w-0 flex-1"}>
        <span className={`body-prominent block ${labelColor}`}>{label}</span>
        {sublabel && (
          <span className="body-small mt-0.5 block text-foreground-muted">{sublabel}</span>
        )}
      </span>
      {hasValue && (
        <span
          title={typeof value === "string" ? value : undefined}
          className="body-normal min-w-0 flex-1 truncate whitespace-nowrap text-right text-foreground-muted"
        >
          {value}
        </span>
      )}
      {end}
    </>
  );

  const cls = [
    "flex min-h-11 w-full items-center gap-3 px-4 py-3 text-left transition-colors",
    "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-foreground-red-orange",
    interactive ? "cursor-pointer hover:bg-surface-base-muted active:bg-surface-base-muted" : "",
    disabled ? "cursor-not-allowed opacity-50" : "",
    className,
  ]
    .filter(Boolean)
    .join(" ");

  const common = {
    className: cls,
    "data-find": findId,
    "aria-description": ariaDescription,
  };

  if (kind === "a") {
    return (
      <a
        {...common}
        aria-disabled={disabled || undefined}
        role={disabled ? "link" : undefined}
        href={disabled ? undefined : href}
        target={external ? "_blank" : undefined}
        rel={external ? "noopener noreferrer" : undefined}
      >
        {content}
      </a>
    );
  }
  if (kind === "button") {
    return (
      <button type="button" {...common} aria-disabled={disabled || undefined} onClick={disabled ? undefined : onPress}>
        {content}
      </button>
    );
  }
  return <div {...common}>{content}</div>;
}

/**
 * The full-width hairline between two {@link NavRow}s (`surface-stroke`).
 *
 * @param inset - Ignored (left over from the removed grouped look); kept so
 * existing callers compile.
 */
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export function NavRowDivider(_props: { inset?: "icon" | "none" } = {}) {
  return <div role="presentation" className="border-t border-surface-stroke" />;
}
