import { For, Show, createEffect, createSignal, on } from "solid-js";
import type { DeckStore } from "./hooks/deckStore";

export interface CardListProps {
  store: DeckStore;
}

const PAGE_SIZE = 10;

/**
 * 卡牌列表：左侧垂直导航，每行高度一致，按页分页
 */
export function CardList(props: CardListProps) {
  const { store } = props;
  const [page, setPage] = createSignal(0);

  const totalPages = () =>
    Math.max(1, Math.ceil(store.state.cards.length / PAGE_SIZE));

  const pageCards = () => {
    const start = page() * PAGE_SIZE;
    return store.state.cards.slice(start, start + PAGE_SIZE);
  };

  // 当活动卡牌变化时，自动跳转到其所在页（只响应 activeTab，避免与手动翻页互相干扰）
  createEffect(
    on(
      () => store.state.activeTab,
      (tab) => {
        setPage(Math.floor(tab / PAGE_SIZE));
      },
    ),
  );

  return (
    <nav class="w-44 shrink-0 border-r border-gray-200 pr-3 flex flex-col">
      <div class="flex flex-col gap-1 flex-1">
        <For each={pageCards()}>
          {(card, index) => {
            const globalIndex = () => page() * PAGE_SIZE + index();
            const active = store.state.activeTab === globalIndex();
            return (
              <button
                onClick={() => store.actions.setActiveTab(globalIndex())}
                class={`flex items-center gap-2 w-full text-left px-3 py-2 rounded text-sm font-medium transition-colors cursor-pointer ${
                  active
                    ? "bg-blue-100 text-blue-600"
                    : "text-gray-600 hover:bg-gray-100"
                }`}
              >
                <span class="shrink-0 text-xs text-gray-400 tabular-nums w-5">
                  {globalIndex() + 1}
                </span>
                <span class="truncate">
                  {card.label || card.name || `Card ${globalIndex() + 1}`}
                </span>
              </button>
            );
          }}
        </For>
      </div>

      <Show when={totalPages() > 1}>
        <div class="flex items-center justify-between mt-2 pt-2 border-t border-gray-200">
          <button
            onClick={() => setPage(Math.max(0, page() - 1))}
            disabled={page() === 0}
            class="px-2 py-1 rounded text-sm text-gray-600 hover:bg-gray-100 disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer"
          >
            ‹
          </button>
          <span class="text-xs text-gray-500 tabular-nums">
            {page() + 1} / {totalPages()}
          </span>
          <button
            onClick={() => setPage(Math.min(totalPages() - 1, page() + 1))}
            disabled={page() >= totalPages() - 1}
            class="px-2 py-1 rounded text-sm text-gray-600 hover:bg-gray-100 disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer"
          >
            ›
          </button>
        </div>
      </Show>
    </nav>
  );
}
