import { useState } from "react";
import { InboxRow, type Accent } from "./InboxRow";
import type { InboxClaimRow, InboxCandidateRow } from "@/lib/inbox-api";
import { cn } from "@/lib/utils";

export type LaneRow = InboxClaimRow | InboxCandidateRow;

const ACCENT_COLOR: Record<Accent, string> = {
  oxblood: "var(--tt-oxblood)",
  amber: "var(--tt-amber)",
  "ink-blue": "var(--tt-ink-blue)",
  muted: "var(--tt-muted)",
};

/**
 * Custom checkbox cell — a small square that picks up the lane's accent
 * when selected. Built on a native `<input type="checkbox">` so the
 * accessibility role and label-by-id wiring are free (the test harness
 * looks the cell up with `screen.getByRole("checkbox")`).
 */
function RowCheckbox({
  id,
  checked,
  onToggle,
}: {
  id: string;
  checked: boolean;
  onToggle: () => void;
}) {
  return (
    <label
      className="flex shrink-0 items-center justify-center cursor-pointer select-none"
      style={{ width: 32 }}
    >
      <span className="relative inline-flex items-center justify-center">
        <input
          type="checkbox"
          aria-label={`Select ${id}`}
          checked={checked}
          onChange={onToggle}
          onClick={(e) => e.stopPropagation()}
          className="peer sr-only"
        />
        <span
          aria-hidden
          className={cn(
            "block h-3.5 w-3.5 rounded-[3px] border transition-all duration-100",
            checked
              ? "bg-[color:var(--tt-amber)] border-[color:var(--tt-amber)] shadow-[0_0_8px_-1px_var(--tt-amber)]"
              : "border-[color:var(--tt-muted)] bg-transparent peer-hover:border-[color:var(--tt-ink-dim)] peer-focus-visible:ring-2 peer-focus-visible:ring-[color:var(--tt-amber)] peer-focus-visible:ring-offset-2 peer-focus-visible:ring-offset-[color:var(--tt-bg-elev)]"
          )}
        />
        {checked ? (
          <svg
            aria-hidden
            viewBox="0 0 12 12"
            className="pointer-events-none absolute h-2.5 w-2.5 text-[color:var(--tt-bg)]"
            fill="none"
            stroke="currentColor"
            strokeWidth="2.5"
            strokeLinecap="round"
            strokeLinejoin="round"
          >
            <polyline points="2.5,6.5 5,9 9.5,3.5" />
          </svg>
        ) : null}
      </span>
    </label>
  );
}

export function Lane({
  name,
  accent,
  rows,
  onRowClick,
  onSelectionChange,
}: {
  name: string;
  accent: Accent;
  rows: LaneRow[];
  onRowClick: (row: LaneRow) => void;
  onSelectionChange?: (ids: string[]) => void;
}) {
  const [selected, setSelected] = useState<Set<string>>(new Set());

  function rowId(row: LaneRow): string {
    return row.kind === "remit" ? (row as InboxCandidateRow).payer_claim_control_number : row.id;
  }

  function toggle(id: string) {
    const next = new Set(selected);
    if (next.has(id)) next.delete(id);
    else next.add(id);
    setSelected(next);
    onSelectionChange?.(Array.from(next));
  }

  const accentColor = ACCENT_COLOR[accent];

  return (
    <section
      className="flex-1 min-w-[280px] flex flex-col rounded-md overflow-hidden"
      style={{
        background: "var(--tt-bg-elev)",
        border: "1px solid hsl(220 8% 18%)",
        boxShadow:
          "inset 0 1px 0 0 hsl(0 0% 100% / 0.03), 0 1px 2px 0 hsl(0 0% 0% / 0.4)",
      }}
      data-lane={name.toLowerCase()}
    >
      <header
        className="px-3 py-2.5 flex items-baseline justify-between gap-2"
        style={{
          borderBottom: "1px solid hsl(220 8% 16%)",
          background:
            "linear-gradient(180deg, hsl(220 16% 11%) 0%, hsl(220 18% 9%) 100%)",
        }}
      >
        <div className="flex items-center gap-2">
          <span
            aria-hidden
            className="inline-block h-2 w-2 rounded-full"
            style={{
              background: accentColor,
              boxShadow: `0 0 8px ${accentColor}`,
            }}
          />
          <h2
            className="mono uppercase"
            style={{
              color: "var(--tt-ink)",
              fontSize: 11,
              letterSpacing: "0.18em",
              fontWeight: 600,
            }}
          >
            {name}
          </h2>
        </div>
        <span
          className="mono tabular-nums"
          style={{
            color: "var(--tt-amber)",
            fontSize: 18,
            fontWeight: 600,
            lineHeight: 1,
          }}
        >
          {rows.length}
        </span>
      </header>

      {rows.length === 0 ? (
        <p
          className="px-4 py-6 mono text-center"
          style={{ color: "var(--tt-muted)", fontSize: 11, letterSpacing: "0.06em" }}
        >
          Nothing here.
        </p>
      ) : (
        <div className="w-full">
          {rows.map((row, idx) => {
            const id = rowId(row);
            const isSelected = selected.has(id);
            return (
              <div
                key={id}
                className={cn(
                  "group flex items-stretch transition-colors",
                  isSelected
                    ? "bg-[color:var(--tt-amber)]/8"
                    : idx % 2 === 0
                      ? "bg-transparent"
                      : "bg-white/[0.015]",
                  "hover:bg-[color:var(--tt-amber)]/5"
                )}
                style={{ borderBottom: "1px solid hsl(220 8% 14%)" }}
              >
                <RowCheckbox
                  id={id}
                  checked={isSelected}
                  onToggle={() => toggle(id)}
                />
                <div className="flex-1 min-w-0">
                  <InboxRow row={row} accent={accent} onClick={() => onRowClick(row)} />
                </div>
              </div>
            );
          })}
        </div>
      )}
    </section>
  );
}
