import { useState, useEffect } from "react";
import { Plus } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useAppStore } from "@/stores/app-store";
import { BoardCard } from "@/components/boards/BoardCard";
import { NewBoardDialog } from "@/components/boards/NewBoardDialog";
import { ImportExportButtons } from "@/components/import-export/ImportExportButtons";

export function BoardList() {
  const boards = useAppStore((s) => s.boards);
  const [dialogOpen, setDialogOpen] = useState(false);

  // Listen for custom event to open new board dialog from command palette
  useEffect(() => {
    function handleOpenDialog() {
      setDialogOpen(true);
    }
    document.addEventListener("open-new-board-dialog", handleOpenDialog);
    return () => {
      document.removeEventListener("open-new-board-dialog", handleOpenDialog);
    };
  }, []);

  if (boards.length === 0) {
    return (
      <>
        <div className="flex h-full flex-col items-center justify-center gap-4">
          <p className="font-mono text-sm text-pylon-text-secondary">
            Create your first board
          </p>
          <div className="flex items-center gap-2">
            <Button onClick={() => setDialogOpen(true)}>
              <Plus className="size-4" />
              New Board
            </Button>
            <ImportExportButtons />
          </div>
        </div>
        <NewBoardDialog open={dialogOpen} onOpenChange={setDialogOpen} />
      </>
    );
  }

  return (
    <>
      <div className="h-full overflow-y-auto p-6">
        {/* Heading row */}
        <div className="mb-4 flex items-center justify-between">
          <h2 className="font-mono text-xs font-semibold uppercase tracking-widest text-pylon-text-secondary">
            Your Boards
          </h2>
          <div className="flex items-center gap-2">
            <ImportExportButtons />
            <Button size="sm" onClick={() => setDialogOpen(true)}>
              <Plus className="size-4" />
              New
            </Button>
          </div>
        </div>

        {/* Board grid */}
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
          {boards.map((board, index) => (
            <BoardCard key={board.id} board={board} index={index} />
          ))}
        </div>
      </div>

      <NewBoardDialog open={dialogOpen} onOpenChange={setDialogOpen} />
    </>
  );
}
