"use client";

import { useState, type CSSProperties, type ReactNode } from "react";
import { MeasurementField } from "@enode/ui/measurement-field";
import { Eyebrow, LOOK } from "../live/look";
import { TAP_TARGET } from "../tap-target";
import { useSettingsLook } from "./settings-look";

// The rows a settings screen or a form is made of. Each is purely
// presentational — all copy is passed in as props (so callers own i18n via
// t(...)).
//
// Two families stand here, and they are one idea at two densities:
//
//   • `SettingsGroup` / `SettingRow` / `ValueButton` — the general row: any
//     control at the right of a label and its hint, or under them. Roomy
//     (px-5 py-4), in a panel with a label in small capitals over it. New
//     forms are made of these.
//   • `ToggleRow` / `NumberRow` / `SliderRow` — rows with their
//     control built in, compact (px-4 py-3), composed inside the
//     `Card`/`RowDivider` list-row system from @enode/ui/list-rows. The
//     account settings and the drawers are made of these.
//
// See docs/components.md ("Form parts") for which to take.

// ── The general row ─────────────────────────────────────────────────────────

/**
 * A group of {@link SettingRow}s: a label in small capitals over one panel,
 * with a rule between its rows.
 */
export function SettingsGroup({
  title,
  children,
  testID,
}: {
  /** The group's label; without one the panel stands alone. */
  title?: ReactNode;
  children: ReactNode;
  /** Becomes `data-testid`. */
  testID?: string;
}) {
  return (
    <section data-testid={testID}>
      {title && (
        <Eyebrow as="h2" className="mb-2 px-1">
          {title}
        </Eyebrow>
      )}
      <div className={`${LOOK.panel} divide-y divide-surface-stroke`}>
        {children}
      </div>
    </section>
  );
}

/**
 * One setting: on the left what it is, in plain words, on the right what it
 * is set to, as the control that changes it. So a form reads top to bottom as
 * "this is set to that", and nothing that can be changed is hidden in running
 * text.
 *
 * `children` is the control and stands at the right of the label; with
 * `below` it stands under the label and takes the row's width, for a control
 * that needs the room (a row of chips, a text field, a list). A control that
 * does not fit beside the label wraps under it by itself. `dense` rows stand
 * closer together, for a long list of short settings (a session's rules).
 */
export function SettingRow({
  label,
  hint,
  below = false,
  dense = false,
  children,
  testID,
}: {
  label: ReactNode;
  /** One quiet line under the label: what the setting does. */
  hint?: ReactNode;
  below?: boolean;
  dense?: boolean;
  children: ReactNode;
  /** Becomes `data-testid`. */
  testID?: string;
}) {
  const screen = useSettingsLook() === "screen";
  if (screen) {
    const column = (
      <div className="min-w-0 flex-1">
        <h3 className="body-prominent text-foreground-default">{label}</h3>
        {hint && (
          <p className="body-small mt-0.5 text-foreground-muted">{hint}</p>
        )}
      </div>
    );
    return (
      <div data-testid={testID} className="min-h-11 px-4 py-3">
        {below ? (
          <>
            {column}
            <div className="mt-3">{children}</div>
          </>
        ) : (
          <div className="flex w-full items-center gap-3">
            {column}
            <div className="flex max-w-full shrink-0 items-center gap-2">
              {children}
            </div>
          </div>
        )}
      </div>
    );
  }
  const name = (
    <div className="min-w-0">
      <h3 className="body-prominent text-foreground-default">{label}</h3>
      {hint && <p className={`mt-0.5 ${LOOK.caption}`}>{hint}</p>}
    </div>
  );
  return (
    <div data-testid={testID} className={`px-5 ${dense ? "py-2.5" : "py-4"}`}>
      {below ? (
        <>
          {name}
          <div className="mt-3">{children}</div>
        </>
      ) : (
        <div className="flex flex-wrap items-center justify-between gap-x-6 gap-y-2">
          <div className="min-w-0 flex-1 basis-40">{name}</div>
          <div className="flex max-w-full shrink-0 items-center gap-2">
            {children}
          </div>
        </div>
      )}
    </div>
  );
}

/**
 * What a setting is set to, as the button that opens its choices: the value
 * and an arrow down, round and outlined, so it reads as a control at a glance.
 * It is 32 px high; a finger gets 44 (`TAP_TARGET`).
 *
 * @remarks
 * It says `aria-haspopup="dialog"`: open a sheet, a drawer or a picker from
 * `onClick`, not a page. One that opens a `ChoiceMenu` says `popup="listbox"`
 * and whether the menu is open (`expanded`).
 */
export function ValueButton({
  children,
  onClick,
  part,
  popup = "dialog",
  expanded,
}: {
  children: ReactNode;
  onClick: () => void;
  /** Becomes `data-part`: which part of a larger setting the button changes. */
  part?: string;
  /** What it opens: a dialog (a sheet, a drawer) or a list of choices. */
  popup?: "dialog" | "listbox";
  /** Whether what it opens is open; left out where it is not tracked. */
  expanded?: boolean;
}) {
  return (
    <button
      type="button"
      onClick={onClick}
      aria-haspopup={popup}
      aria-expanded={expanded}
      data-part={part}
      className={`${TAP_TARGET} clickable-small inline-flex max-w-full items-center gap-2 rounded-full border border-surface-stroke bg-surface-base-muted py-1.5 pl-4 pr-3 text-left text-foreground-default transition-colors hover:border-foreground-muted`}
    >
      <span className="min-w-0 first-letter:uppercase">{children}</span>
      <svg
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        strokeWidth={2}
        strokeLinecap="round"
        strokeLinejoin="round"
        aria-hidden="true"
        className="size-4 shrink-0 text-foreground-muted"
      >
        <path d="m6 9 6 6 6-6" />
      </svg>
    </button>
  );
}

/**
 * The class of a quiet, round text control inside a form: "More rules",
 * "Show everyone again". It is a line of small text, 25 px high; a finger
 * gets 44 (`TAP_TARGET`).
 */
export const FORM_LINK = `${TAP_TARGET} body-small -mx-2 rounded-full px-2 py-1 text-foreground-muted underline-offset-2 transition-colors hover:text-foreground-default hover:underline`;

// ── Rows with their control built in ────────────────────────────────────────

/** Compact iOS-style switch: red-orange when on, neutral muted when off. */
export function Toggle({
  checked,
  onChange,
  ariaLabel,
  disabled,
}: {
  checked: boolean;
  onChange: (next: boolean) => void;
  ariaLabel: string;
  disabled?: boolean;
}) {
  return (
    <button
      type="button"
      role="switch"
      aria-checked={checked}
      aria-label={ariaLabel}
      disabled={disabled}
      onClick={() => onChange(!checked)}
      className={`relative inline-flex h-7 w-12 shrink-0 items-center rounded-full transition-colors after:absolute after:-inset-2 after:content-[''] disabled:opacity-50 ${
        checked ? "bg-foreground-red-orange" : "bg-surface-stroke"
      }`}
    >
      <span
        className={`inline-block size-5 rounded-full bg-white shadow transition-transform ${
          checked ? "translate-x-6" : "translate-x-1"
        }`}
      />
    </button>
  );
}

/** A labelled row carrying a {@link Toggle} on the trailing edge. */
export function ToggleRow({
  label,
  value,
  onChange,
  disabled,
  description,
}: {
  label: string;
  value: boolean;
  onChange: (next: boolean) => void;
  disabled?: boolean;
  /** Optional one-line explainer rendered muted under the label. */
  description?: string;
}) {
  if (useSettingsLook() === "screen") {
    return (
      <label
        className={`flex min-h-11 w-full items-center gap-3 px-4 py-3 ${disabled ? "" : "cursor-pointer"}`}
      >
        <span className="min-w-0 flex-1">
          <span className="body-prominent block">{label}</span>
          {description && (
            <span className="body-small mt-0.5 block text-foreground-muted">
              {description}
            </span>
          )}
        </span>
        <Toggle
          checked={value}
          onChange={onChange}
          ariaLabel={label}
          disabled={disabled}
        />
      </label>
    );
  }
  return (
    <label
      className={`block min-h-11 px-4 py-3 ${disabled ? "" : "cursor-pointer"}`}
    >
      <span className="flex items-center justify-between gap-3">
        <span className="body-prominent">{label}</span>
        <Toggle
          checked={value}
          onChange={onChange}
          ariaLabel={label}
          disabled={disabled}
        />
      </span>
      {description && (
        <span className="body-small mt-1 block text-foreground-muted">
          {description}
        </span>
      )}
    </label>
  );
}

/**
 * Labeled slider row in the Toggle's visual language: the same light-grey
 * track (`surface-stroke`), the filled portion in red-orange, and a white
 * shadowed knob. The current value renders right-aligned above the slider;
 * with `onReset` it becomes a tap-to-reset button.
 */
export function SliderRow({
  label,
  value,
  min,
  max,
  step,
  onChange,
  valueLabel,
  onReset,
  resetLabel,
  description,
}: {
  label: string;
  value: number;
  min: number;
  max: number;
  step: number;
  onChange: (next: number) => void;
  /** Display form of the current value, e.g. "110%". */
  valueLabel: string;
  /** When set, tapping the value label resets to the default. */
  onReset?: () => void;
  /** Accessible label for the reset button; required with `onReset`. */
  resetLabel?: string;
  /** Optional one-line explainer rendered muted under the label. */
  description?: string;
}) {
  const pct = ((value - min) / (max - min)) * 100;
  const screen = useSettingsLook() === "screen";
  return (
    <div className={screen ? "min-h-11 px-4 py-3" : "px-4 py-3"}>
      <div className="flex items-center justify-between gap-3">
        <span className="body-prominent">{label}</span>
        {onReset ? (
          <button
            type="button"
            onClick={onReset}
            aria-label={resetLabel}
            // -mr-2 + justify-end: the value's right edge lines up with the
            // trailing values of the other rows, the 44 px area reaches out.
            className="body-small -mr-2 inline-flex min-h-11 min-w-11 items-center justify-end rounded-full px-2 py-0.5 text-foreground-muted hover:bg-surface-base-muted"
          >
            {valueLabel}
          </button>
        ) : (
          <span className="body-small text-foreground-muted">{valueLabel}</span>
        )}
      </div>
      {description && (
        <p
          className={`body-small text-foreground-muted ${screen ? "mt-0.5" : "mt-1"}`}
        >
          {description}
        </p>
      )}
      <input
        type="range"
        min={min}
        max={max}
        step={step}
        value={value}
        onChange={(e) => onChange(Number(e.target.value))}
        aria-label={label}
        // Fill percentage for the WebKit track gradient — WebKit has no
        // ::-webkit-range-progress, so the fill is painted as a hard-stop
        // gradient up to the knob position.
        style={{ "--slider-fill": `${pct}%` } as CSSProperties}
        // h-11 = 44 px touch target; -mt-1/-mb-2 keep the old 28 px of layout.
        className="-mb-2 -mt-1 block h-11 w-full cursor-pointer appearance-none bg-transparent
          [&::-webkit-slider-runnable-track]:h-2
          [&::-webkit-slider-runnable-track]:rounded-full
          [&::-webkit-slider-runnable-track]:bg-[linear-gradient(to_right,var(--foreground-red-orange)_var(--slider-fill),var(--surface-stroke)_var(--slider-fill))]
          [&::-webkit-slider-thumb]:-mt-2
          [&::-webkit-slider-thumb]:size-6
          [&::-webkit-slider-thumb]:appearance-none
          [&::-webkit-slider-thumb]:rounded-full
          [&::-webkit-slider-thumb]:bg-white
          [&::-webkit-slider-thumb]:shadow
          [&::-moz-range-track]:h-2
          [&::-moz-range-track]:rounded-full
          [&::-moz-range-track]:bg-surface-stroke
          [&::-moz-range-progress]:h-2
          [&::-moz-range-progress]:rounded-full
          [&::-moz-range-progress]:bg-foreground-red-orange
          [&::-moz-range-thumb]:size-6
          [&::-moz-range-thumb]:rounded-full
          [&::-moz-range-thumb]:border-0
          [&::-moz-range-thumb]:bg-white
          [&::-moz-range-thumb]:shadow"
      />
    </div>
  );
}

/**
 * In-cell editable number, displayed as "<value> <unit>" with the input
 * occupying the value position. Commits on blur so an in-flight edit isn't
 * PUT'd on every keystroke. When `min`/`max` are set, the committed value
 * is clamped to that window — out-of-range typos snap to the nearest bound
 * instead of silently flowing through to the server. The `unit` renders as
 * passed (no case change); pass a core `unitSymbol()` for the uppercase house style.
 */
export function NumberRow({
  label,
  value,
  unit,
  min,
  max,
  onChange,
  disabled,
  description,
}: {
  label: string;
  value: number;
  unit?: string;
  min?: number;
  max?: number;
  onChange: (next: number) => void;
  disabled?: boolean;
  /** Optional one-line explainer rendered muted under the label. */
  description?: string;
}) {
  const [raw, setRaw] = useState(String(value));
  const [prevValue, setPrevValue] = useState(value);
  // Re-init the input when the stored value changes (e.g. after a PUT
  // round-trip) and the user isn't editing this field.
  if (value !== prevValue) {
    setPrevValue(value);
    setRaw(String(value));
  }

  function commit() {
    const parsed = Number(raw);
    if (!Number.isFinite(parsed)) {
      setRaw(String(value));
      return;
    }
    let next = parsed;
    if (min != null) next = Math.max(min, next);
    if (max != null) next = Math.min(max, next);
    setRaw(String(next));
    if (next === value) return;
    onChange(next);
  }

  const screen = useSettingsLook() === "screen";
  return (
    <div
      className={`flex items-center gap-3 px-4 py-3 ${screen ? "min-h-11 w-full" : "justify-between"}`}
    >
      <span className={screen ? "min-w-0 flex-1" : "min-w-0"}>
        <span className="body-prominent block">{label}</span>
        {description && (
          <span
            className={`body-small block text-foreground-muted ${screen ? "mt-0.5" : ""}`.trim()}
          >
            {description}
          </span>
        )}
      </span>
      <div className="flex items-center gap-1.5">
        <MeasurementField
          inputMode="decimal"
          value={raw}
          onChange={(e) => setRaw(e.target.value)}
          onBlur={commit}
          onFocus={(e) => e.currentTarget.select()}
          disabled={disabled}
          aria-label={label}
          className={screen ? "min-h-11 w-16" : "w-16"}
        />
        {unit && (
          <span className="stat-small text-foreground-muted">
            {unit}
          </span>
        )}
      </div>
    </div>
  );
}
