import { Link, useNavigate } from "@tanstack/react-router";
import { Plus } from "lucide-react";
import { toast } from "sonner";
import { Empty, Page, Panel } from "@/components/page";
import { Button } from "@/components/ui/button";
import { Tag } from "@/components/ui/tag";
import { useWorkspace } from "@/lib/store";
import type { Board, BoardKind } from "@/lib/types";

export function BoardIndex({ kind }: { kind: BoardKind }) {
  const navigate = useNavigate();
  const allBoards = useWorkspace((s) => s.boards);
  const projects = useWorkspace((s) => s.projects);
  const addBoard = useWorkspace((s) => s.addBoard);
  const removeBoard = useWorkspace((s) => s.removeBoard);
  const boards = allBoards.filter((b) => b.kind === kind);
  const noun = kind === "flow" ? "flowchart" : "board";

  const create = () => {
    const id = addBoard(kind);
    toast(`New ${noun} opened`);
    void navigate({
      to: kind === "flow" ? "/flows/$flowId" : "/boards/$boardId",
      params: kind === "flow" ? { flowId: id } : { boardId: id },
    });
  };

  return (
    <Page
      eyebrow="Draw"
      title={kind === "flow" ? "Flowcharts" : "Whiteboards"}
      description={
        kind === "flow"
          ? "Map a process, then promote a node into a task or a note. The diagram stays the source of truth."
          : "Stickies, shapes, and pen. Anything on the wall can become work in the book."
      }
      actions={
        <Button variant="primary" onClick={create}>
          <Plus className="size-3.5" />
          New {noun}
        </Button>
      }
    >
      {boards.length === 0 ? (
        <Panel>
          <Empty title={`No ${noun}s yet`} body={`Create one and start placing nodes.`} />
        </Panel>
      ) : (
        <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-3">
          {boards.map((b) => (
            <BoardCard
              key={b.id}
              board={b}
              projectName={projects.find((p) => p.id === b.projectId)?.name}
              onDelete={() => {
                if (window.confirm(`Delete “${b.title}”?`)) removeBoard(b.id);
              }}
            />
          ))}
        </div>
      )}
    </Page>
  );
}

function BoardCard({
  board,
  projectName,
  onDelete,
}: {
  board: Board;
  projectName?: string;
  onDelete: () => void;
}) {
  const href =
    board.kind === "flow"
      ? { to: "/flows/$flowId" as const, params: { flowId: board.id } }
      : { to: "/boards/$boardId" as const, params: { boardId: board.id } };
  return (
    <article className="border border-line rounded-md bg-surface overflow-hidden hover:shadow-[var(--shadow-pop)] transition-shadow">
      <Link {...href} className="block hover:no-underline text-ink">
        <BoardThumb board={board} />
        <div className="px-3 py-2.5 border-t border-line">
          <div className="flex items-center gap-2">
            <strong className="text-sm font-semibold truncate">{board.title}</strong>
            <Tag>{board.kind}</Tag>
          </div>
          <div className="mt-1 text-xs text-ink-2 flex items-center gap-2">
            <span>{projectName ?? "Unfiled"}</span>
            <span className="font-mono tabular-nums">{board.nodes.length} nodes</span>
          </div>
        </div>
      </Link>
      <div className="px-3 pb-3">
        <Button size="sm" variant="ghost" onClick={onDelete}>
          Delete
        </Button>
      </div>
    </article>
  );
}

function BoardThumb({ board }: { board: Board }) {
  const maxX = Math.max(400, ...board.nodes.map((n) => n.x + n.w), 1);
  const maxY = Math.max(240, ...board.nodes.map((n) => n.y + n.h), 1);
  return (
    <svg viewBox={`0 0 ${maxX} ${maxY}`} className="w-full h-32 bg-sunken block">
      {board.nodes.map((n) => (
        <rect
          key={n.id}
          x={n.x}
          y={n.y}
          width={n.w}
          height={n.h}
          rx={6}
          fill={n.fill ?? "var(--color-surface)"}
          stroke="var(--color-line)"
        />
      ))}
    </svg>
  );
}
