"use client";

import { useMemo } from "react";

import { AppShell } from "@/components/AppShell";
import type { ForeshadowView, ProjectResponse } from "@/lib/api/types";
import {
  LANES,
  groupByStatus,
  type ForeshadowStatus,
} from "@/lib/foreshadow/board";
import { useForeshadow } from "@/lib/foreshadow/useForeshadow";
import { KanbanColumn } from "./KanbanColumn";
import { RegisterForm } from "./RegisterForm";

interface ForeshadowBoardProps {
  project: ProjectResponse;
  initialItems: ForeshadowView[];
}

// 伏笔看板主体（UX §6.8）：四泳道 + 登记/状态变更交互。
// RSC 取全量种入；Client 承载登记/转移（乐观 + 回滚 + Toast）。
export function ForeshadowBoard({
  project,
  initialItems,
}: ForeshadowBoardProps) {
  const { items, busy, register, transition } = useForeshadow(initialItems);
  const lanes = useMemo(() => groupByStatus(items), [items]);

  const onTransition = (
    code: string,
    toStatus: ForeshadowStatus | null,
    progressNote: string,
  ): void => {
    void transition(code, {
      projectId: project.id,
      toStatus,
      progressEntry: progressNote ? { note: progressNote } : null,
    });
  };

  return (
    <AppShell
      title={`〈${project.title}〉`}
      subtitle="伏笔看板"
      projectId={project.id}
      activeNav="foreshadow"
    >
      <div className="flex h-[calc(100vh-var(--chrome,4rem))] flex-col p-4">
        <div className="mb-4 flex items-start justify-between gap-4">
          <h1 className="font-serif text-lg text-ink">伏笔看板</h1>
          <RegisterForm
            projectId={project.id}
            busy={busy}
            onRegister={register}
          />
        </div>
        <div className="grid min-h-0 flex-1 grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-4">
          {LANES.map((status) => (
            <KanbanColumn
              key={status}
              status={status}
              items={lanes[status]}
              busy={busy}
              onTransition={onTransition}
            />
          ))}
        </div>
      </div>
    </AppShell>
  );
}
