"use client";

import { useEffect, useRef, useState } from "react";
import { useTranslation } from "@enode/core/translations/hooks";
import {
  DragHandleIcon,
  EyeFillIcon,
  EyeSlashFillIcon,
  RectangleSplit3x1FillIcon,
} from "@enode/ui/icons";
import {
  MenuPanelAction,
  MenuPanelFootnote,
  MenuPanelHeader,
  MenuPanelSection,
  MenuPopover,
} from "@enode/ui/menu-panel";
import {
  activeColumnView,
  type ColumnOption,
  type ColumnView,
  type TableColumns,
} from "./table-columns";

// The "Columns" control of a table: a small icon trigger — meant for the empty
// header cell above the row actions — and a popover in which the coach shows,
// hides and arranges the columns (see ./table-columns). Every change applies at
// once; there is nothing to confirm.
//
// The popover is the shared `MenuPopover` (`@enode/ui/menu-panel`) — the same
// panel, title row, section headings and footnote as the search card's
// "Filters" menu.

export function ColumnsMenu({
  columns,
  views = [],
}: {
  columns: TableColumns;
  /** Ready-made arrangements offered above the list. */
  views?: readonly ColumnView[];
}) {
  const { t } = useTranslation();
  const [open, setOpen] = useState(false);
  const triggerRef = useRef<HTMLButtonElement>(null);

  const view = activeColumnView(columns.options, views, columns.shown);
  const byKey = new Map(columns.options.map((o) => [o.key, o]));
  const shownOptions = columns.shown.flatMap((key) => {
    const option = byKey.get(key);
    return option ? [option] : [];
  });
  const hiddenOptions = columns.options.filter(
    (o) => !columns.shown.includes(o.key),
  );

  // Dragging a row by its handle: the row under the pointer names the place.
  const listRef = useRef<HTMLUListElement>(null);
  const [dragKey, setDragKey] = useState<string | null>(null);
  useEffect(() => {
    if (dragKey == null) return;
    function onMove(e: PointerEvent) {
      const rows = listRef.current?.querySelectorAll<HTMLElement>("[data-column]");
      if (!rows || dragKey == null) return;
      rows.forEach((row, index) => {
        const rect = row.getBoundingClientRect();
        if (e.clientY >= rect.top && e.clientY < rect.bottom) {
          columns.move(dragKey, index);
        }
      });
    }
    function onUp() {
      setDragKey(null);
    }
    document.addEventListener("pointermove", onMove);
    document.addEventListener("pointerup", onUp);
    document.addEventListener("pointercancel", onUp);
    return () => {
      document.removeEventListener("pointermove", onMove);
      document.removeEventListener("pointerup", onUp);
      document.removeEventListener("pointercancel", onUp);
    };
  }, [dragKey, columns]);

  // Keeps keyboard focus on the handle of the column that was just moved.
  const refocusKey = useRef<string | null>(null);
  useEffect(() => {
    const key = refocusKey.current;
    if (key == null) return;
    refocusKey.current = null;
    listRef.current
      ?.querySelector<HTMLElement>(`[data-handle="${CSS.escape(key)}"]`)
      ?.focus();
  });

  function moveByKeyboard(key: string, delta: number) {
    refocusKey.current = key;
    columns.move(key, columns.shown.indexOf(key) + delta);
  }

  return (
    <>
      <button
        ref={triggerRef}
        type="button"
        onClick={(e) => {
          // Lives in a table header: never toggle a sort or a row behind it.
          e.stopPropagation();
          setOpen((v) => !v);
        }}
        aria-haspopup="dialog"
        aria-expanded={open}
        aria-label={t("Columns")}
        title={t("Columns")}
        className={`inline-flex size-8 items-center justify-center rounded-full transition-colors hover:bg-surface-base-muted hover:text-foreground-default ${
          open || !columns.isDefault ? "text-foreground-default" : "text-foreground-muted"
        }`}
      >
        <RectangleSplit3x1FillIcon className="size-4" />
      </button>
      <MenuPopover
        open={open}
        onClose={() => setOpen(false)}
        triggerRef={triggerRef}
        label={t("Columns")}
      >
        <MenuPanelHeader
          title={t("Columns")}
          action={
            <MenuPanelAction onClick={columns.reset} disabled={columns.isDefault}>
              {t("Reset")}
            </MenuPanelAction>
          }
        />

        {views.length > 0 && (
          <div
            role="group"
            aria-label={t("Ready-made views")}
            className="mb-1.5 flex flex-wrap gap-1.5 border-b border-surface-stroke px-1 pb-2.5"
          >
            {views.map((v) => (
              <ViewChip
                key={v.key}
                label={v.label}
                active={view?.key === v.key}
                onClick={() => columns.apply(v.columns)}
              />
            ))}
          </div>
        )}

        <ul ref={listRef}>
          {shownOptions.map((option) => (
            <ColumnRow
              key={option.key}
              option={option}
              shown
              dragging={dragKey === option.key}
              onToggle={() => columns.toggle(option.key)}
              onGrab={() => setDragKey(option.key)}
              onStep={(delta) => moveByKeyboard(option.key, delta)}
            />
          ))}
        </ul>

        {/* The columns to add, by kind — with many on offer, a group
            name finds one faster than a long flat list. */}
        {hiddenGroups(hiddenOptions, t("More columns")).map(([group, options]) => (
          <MenuPanelSection key={group} label={group}>
            {options.map((option) => (
              <ColumnRow
                key={option.key}
                option={option}
                shown={false}
                onToggle={() => columns.toggle(option.key)}
              />
            ))}
          </MenuPanelSection>
        ))}

        <MenuPanelFootnote>
          {t("Drag to arrange. Saved for you in this browser.")}
        </MenuPanelFootnote>
      </MenuPopover>
    </>
  );
}

function ViewChip({
  label,
  active,
  onClick,
}: {
  label: string;
  active: boolean;
  onClick: () => void;
}) {
  const className = `clickable-small inline-flex min-h-8 items-center rounded-full border px-3 transition-colors ${
    active
      ? "border-foreground-default bg-foreground-default text-surface-base"
      : "border-surface-stroke text-foreground-muted hover:text-foreground-default"
  }`;
  return (
    <button
      type="button"
      aria-pressed={active}
      onClick={onClick}
      className={className}
    >
      {label}
    </button>
  );
}

function ColumnRow({
  option,
  shown,
  dragging = false,
  onToggle,
  onGrab,
  onStep,
}: {
  option: ColumnOption;
  shown: boolean;
  dragging?: boolean;
  onToggle: () => void;
  onGrab?: () => void;
  onStep?: (delta: number) => void;
}) {
  const { t } = useTranslation();
  const movable = shown && !option.fixed && onGrab != null && onStep != null;
  return (
    <li
      data-column={shown ? option.key : undefined}
      className={`flex min-h-10 items-center gap-1 rounded-lg ${
        dragging ? "bg-surface-base-muted" : ""
      }`}
    >
      {movable ? (
        <button
          type="button"
          data-handle={option.key}
          aria-label={t("Move {column}. Use arrow up and arrow down.", {
            column: option.label,
          })}
          onPointerDown={(e) => {
            e.preventDefault();
            onGrab();
          }}
          onKeyDown={(e) => {
            if (e.key !== "ArrowUp" && e.key !== "ArrowDown") return;
            e.preventDefault();
            onStep(e.key === "ArrowDown" ? 1 : -1);
          }}
          className="flex h-10 w-7 shrink-0 cursor-grab touch-none items-center justify-center rounded-lg text-foreground-more-muted transition-colors hover:text-foreground-default"
        >
          <DragHandleIcon className="size-4" />
        </button>
      ) : (
        <span aria-hidden className="w-7 shrink-0" />
      )}
      <span
        className={`body-normal min-w-0 flex-1 truncate ${
          shown ? "text-foreground-default" : "text-foreground-muted"
        }`}
      >
        {option.label}
      </span>
      {option.fixed ? (
        <span className="body-small pr-2 text-foreground-muted">{t("always shown")}</span>
      ) : (
        // Show / hide, as an eye — the row reads as a list of columns, not a form.
        <button
          type="button"
          role="switch"
          aria-checked={shown}
          aria-label={shown ? t("Hide {column}", { column: option.label }) : t("Show {column}", { column: option.label })}
          onClick={onToggle}
          className={`flex size-10 shrink-0 items-center justify-center rounded-lg transition-colors hover:bg-surface-base-muted ${
            shown ? "text-foreground-default" : "text-foreground-more-muted"
          }`}
        >
          {shown ? <EyeFillIcon className="size-[18px]" /> : <EyeSlashFillIcon className="size-[18px]" />}
        </button>
      )}
    </li>
  );
}

// Hidden options in their groups, in the order the groups first appear;
// ungrouped ones first under `fallback`.
function hiddenGroups(
  options: readonly ColumnOption[],
  fallback: string,
): [string, ColumnOption[]][] {
  const groups = new Map<string, ColumnOption[]>();
  for (const option of options) {
    const name = option.group ?? fallback;
    groups.set(name, [...(groups.get(name) ?? []), option]);
  }
  return [...groups.entries()];
}
