"use client";

import { useState, type ReactNode } from "react";
import { useTranslation } from "@enode/core/translations/hooks";
import { BottomSheetCard } from "@enode/ui/bottom-sheet-card";
import { ArrowDownIcon, CheckIcon, LockFillIcon } from "@enode/ui/icons";
import { LOOK } from "@enode/ui/live/look";
import { SegmentedPicker } from "@enode/ui/segmented-picker";
import { TAP_TARGET } from "@enode/ui/tap-target";
import {
  TableSelectionBar,
  type SelectionActionItem,
  type SelectionApply,
} from "./data-table";
import type { SortState } from "./data-table-view";
import { Button } from "@enode/ui/button";

// Mobile (<md) companions to <DataTable> for the card lists on Users, Exercises
// and History. The table owns sort / count / paging / multi-select on desktop;
// these give the card list the same abilities in a phone-shaped form:
//
//   MobileListToolbar   count line + sort chip (→ MobileSortSheet)
//   MobileSelectionHeader  replaces the toolbar while select mode is on
//   MobileSelectPill    floating "Select" pill that enters select mode
//   MobileSelectionPill the desktop selection pill, compact, in select mode
//   SelectMark          the checkbox drawn inside a selectable card
//   ShowMoreButton + useShowMore  incremental rendering instead of a pager
//
// Select mode follows the workout builder's drawer: one floating pill at the
// bottom whose contents swap — "Select" while browsing, the bulk actions and
// "Done" while selecting.
//
// Everything here is presentational; the page owns sort, selection and the
// select-mode flag, and shares them with its desktop table.

/** One sortable field offered in the mobile sort sheet (a DataTable column key). */
export type MobileSortOption = { key: string; label: string };

/** The mobile sort control: the fields to offer and the page's sort state. */
export type MobileSortProps = {
  title: string;
  // Name of the rows' own order (sort `null`), e.g. "Role, then name".
  defaultLabel: string;
  options: MobileSortOption[];
  value: SortState | null;
  onChange: (next: SortState | null) => void;
};

/**
 * How many cards a mobile list renders, growing by `per` on each "Show more".
 *
 * @remarks Resets to `per` whenever `resetKey` changes — pass a string built
 * from the filters and sort, so a new view starts at the top again (the desktop
 * table's pager snaps back the same way).
 */
export function useShowMore(per: number, resetKey: string) {
  const [state, setState] = useState({ key: resetKey, limit: per });
  // Render-phase reset on a new view (the "adjust state on prop change" idiom).
  if (state.key !== resetKey) setState({ key: resetKey, limit: per });
  const limit = state.key === resetKey ? state.limit : per;
  return {
    limit,
    showMore: () => setState({ key: resetKey, limit: limit + per }),
  };
}

export function ShowMoreButton({
  count,
  onClick,
}: {
  count: number;
  onClick: () => void;
}) {
  const { t } = useTranslation();
  return (
    <button
      type="button"
      onClick={onClick}
      className={`body-prominent w-full ${LOOK.panel} py-3 text-foreground-default transition-colors hover:bg-surface-base-muted`}
    >
      {t("Show {count} more", { count })}
    </button>
  );
}

// The row above a mobile card list: the count line on the left, the sort chip
// on the right.
export function MobileListToolbar({
  summary,
  sort,
}: {
  summary: ReactNode;
  sort?: MobileSortProps;
}) {
  const { t } = useTranslation();
  const [sortOpen, setSortOpen] = useState(false);
  const activeOption = sort?.value
    ? sort.options.find((o) => o.key === sort.value?.key)
    : undefined;
  return (
    <div className="flex min-h-9 items-center justify-between gap-2">
      <p className="body-small min-w-0 truncate text-foreground-muted">
        {summary}
      </p>
      <div className="flex shrink-0 items-center gap-2">
        {sort && (
          <button
            type="button"
            onClick={() => setSortOpen(true)}
            aria-label={t("Sort")}
            className={`${TAP_TARGET} body-small inline-flex items-center gap-1 rounded-full border border-surface-stroke bg-surface-base px-3 py-1.5 text-foreground-default`}
          >
            <span className="max-w-[9rem] truncate">
              {activeOption ? activeOption.label : sort.defaultLabel}
            </span>
            {sort.value && (
              <ArrowDownIcon
                className={`size-3 shrink-0 ${sort.value.dir === "asc" ? "rotate-180" : ""}`}
              />
            )}
          </button>
        )}
      </div>
      {sort && (
        <MobileSortSheet
          {...sort}
          open={sortOpen}
          onClose={() => setSortOpen(false)}
        />
      )}
    </div>
  );
}

// Bottom sheet listing the rows' own order plus each sortable field; a picked
// field gets an ascending/descending switch. Changes apply immediately.
function MobileSortSheet({
  open,
  onClose,
  title,
  defaultLabel,
  options,
  value,
  onChange,
}: MobileSortProps & { open: boolean; onClose: () => void }) {
  const { t } = useTranslation();
  return (
    <BottomSheetCard open={open} onClose={onClose} ariaLabel={title}>
      <div className="flex flex-col gap-4 p-5">
        <h2 className="heading-normal text-foreground-default">{title}</h2>
        <div role="radiogroup" aria-label={title} className="flex flex-col">
          <SortRadio
            label={defaultLabel}
            checked={value == null}
            onSelect={() => onChange(null)}
          />
          {options.map((option) => (
            <SortRadio
              key={option.key}
              label={option.label}
              checked={value?.key === option.key}
              onSelect={() =>
                onChange({ key: option.key, dir: value?.dir ?? "asc" })
              }
            />
          ))}
        </div>
        {value && (
          <SegmentedPicker<SortState["dir"]>
            ariaLabel={t("Sort direction")}
            fullWidth
            value={value.dir}
            onChange={(dir) => onChange({ key: value.key, dir })}
            options={[
              { value: "asc", label: t("Ascending") },
              { value: "desc", label: t("Descending") },
            ]}
          />
        )}
        <Button variant="primary" size="rounded" onClick={onClose}>
          {t("Done")}
        </Button>
      </div>
    </BottomSheetCard>
  );
}

function SortRadio({
  label,
  checked,
  onSelect,
}: {
  label: string;
  checked: boolean;
  onSelect: () => void;
}) {
  return (
    <button
      type="button"
      role="radio"
      aria-checked={checked}
      onClick={onSelect}
      className="body-normal flex items-center justify-between gap-3 border-b border-surface-stroke py-3 text-left text-foreground-default last:border-b-0"
    >
      <span>{label}</span>
      <span
        aria-hidden
        className={`size-5 shrink-0 rounded-full border ${
          checked
            ? "border-[6px] border-foreground-red-orange"
            : "border-surface-stroke"
        }`}
      />
    </button>
  );
}

// Replaces the toolbar while select mode is on: what a tap does now on the
// left, select/deselect-all (over the rendered cards) on the right. The count
// and the way out are the pill's leading circle.
export function MobileSelectionHeader({
  allSelected,
  onToggleAll,
}: {
  allSelected: boolean;
  onToggleAll: () => void;
}) {
  const { t } = useTranslation();
  return (
    <div className="flex min-h-9 items-center justify-between gap-2">
      <span className="body-small min-w-0 truncate text-foreground-muted">
        {t("Tap cards to select them")}
      </span>
      <button
        type="button"
        onClick={onToggleAll}
        className={`${TAP_TARGET} body-small shrink-0 rounded-full border border-surface-stroke bg-surface-base px-3 py-1.5 text-foreground-default`}
      >
        {allSelected ? t("Deselect all") : t("Select all")}
      </button>
    </div>
  );
}

// Where both mobile pills float: centred a fixed distance above the bottom of
// the dashboard `<main>`, the anchor the desktop selection pill uses. The
// wrapper ignores pointers so the cards beside the pill stay tappable.
function FloatingPillSlot({ children }: { children: ReactNode }) {
  return (
    <div className="pointer-events-none absolute inset-x-0 bottom-[max(1.5rem,env(safe-area-inset-bottom))] z-20 flex justify-center px-4 md:hidden">
      {children}
    </div>
  );
}

/**
 * The floating "Select" pill a mobile list shows while browsing — the workout
 * builder's entry into select mode. Give the list a bottom spacer
 * ({@link MOBILE_PILL_SPACER}) so the last card can scroll clear of it.
 */
export function MobileSelectPill({ onSelect }: { onSelect: () => void }) {
  const { t } = useTranslation();
  return (
    <FloatingPillSlot>
      <div className="pointer-events-auto flex items-center rounded-full bg-surface-base p-1.5 shadow-floating ring-1 ring-surface-stroke-muted">
        <button
          type="button"
          onClick={onSelect}
          className={`${TAP_TARGET} clickable-small rounded-full px-4 py-1.5 text-foreground-default transition-colors hover:bg-surface-base-muted`}
        >
          {t("Select")}
        </button>
      </div>
    </FloatingPillSlot>
  );
}

/**
 * The pill that replaces {@link MobileSelectPill} in select mode: the desktop
 * selection pill in its compact form. Takes the same items as the desktop pill
 * — pass only the ones that belong on a phone.
 *
 * @param onClear - the leading count circle, as on desktop: clears the
 *   selection, and here also leaves select mode (desktop has no mode to leave —
 *   its pill simply disappears with the selection).
 */
export function MobileSelectionPill({
  count,
  noun,
  items,
  apply,
  overlay,
  onClear,
}: {
  count: number;
  noun: string;
  items: SelectionActionItem[];
  apply?: SelectionApply;
  overlay?: ReactNode;
  onClear: () => void;
}) {
  return (
    <FloatingPillSlot>
      <TableSelectionBar
        compact
        count={count}
        noun={noun}
        items={items}
        apply={apply}
        overlay={overlay}
        onClear={onClear}
      />
    </FloatingPillSlot>
  );
}

/** Bottom spacer for a list under a floating pill (pill height + its lift). */
export const MOBILE_PILL_SPACER = "h-24";

// The checkbox inside a selectable card. Drawn, not a control: the whole card is
// the toggle (it carries `aria-pressed`), so a nested button would be invalid.
// A locked card (not selectable, e.g. your own row) shows the desktop lock.
export function SelectMark({
  checked,
  locked = false,
}: {
  checked: boolean;
  locked?: boolean;
}) {
  if (locked) {
    return (
      <span
        aria-hidden
        className="flex size-[18px] shrink-0 items-center justify-center rounded-md border border-surface-stroke bg-surface-base text-surface-stroke"
      >
        <LockFillIcon className="size-3" />
      </span>
    );
  }
  return (
    <span
      aria-hidden
      className={`flex size-[18px] shrink-0 items-center justify-center rounded-md border ${
        checked
          ? "border-foreground-red-orange bg-foreground-red-orange text-white"
          : "border-surface-stroke bg-surface-base"
      }`}
    >
      {checked && <CheckIcon className="size-3" />}
    </span>
  );
}

/**
 * Select-mode helpers over the cards a mobile list currently renders: whether
 * all of them are selected, and the next set for a select/deselect-all tap.
 * Mirrors the desktop header checkbox, which acts on the visible page only.
 */
export function toggleAllVisible(
  selected: ReadonlySet<string>,
  visibleKeys: string[],
): { allSelected: boolean; next: () => ReadonlySet<string> } {
  const allSelected =
    visibleKeys.length > 0 && visibleKeys.every((k) => selected.has(k));
  return {
    allSelected,
    next: () => {
      const set = new Set(selected);
      for (const k of visibleKeys) {
        if (allSelected) set.delete(k);
        else set.add(k);
      }
      return set;
    },
  };
}
