"use client";
import { jsx, jsxs } from 'react/jsx-runtime';
import { useState, useCallback, useMemo, useEffect } from 'react';
import { ArrowLeft, Settings, Plus, Pencil, Trash2 } from 'lucide-react';
import { toast } from 'sonner';
import { Button } from '../../../../../../../ui/src/components/button.mjs';
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator } from '../../../../../../../ui/src/components/dropdown-menu.mjs';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '../../../../../../../ui/src/components/dialog.mjs';
import { AlertDialog, AlertDialogContent, AlertDialogHeader, AlertDialogTitle, AlertDialogDescription, AlertDialogFooter, AlertDialogCancel, AlertDialogAction } from '../../../../../../../ui/src/components/alert-dialog.mjs';
import { useSuspenseBoard, useBoardMutations, useColumnMutations, useTaskMutations } from '../../hooks/kanban-hooks.mjs';
import { usePluginOverrides } from '@btst/stack/context';
import { KanbanBoard } from '../shared/kanban-board.mjs';
import { ColumnForm } from '../forms/column-form.mjs';
import { BoardForm } from '../forms/board-form.mjs';
import { TaskForm } from '../forms/task-form.mjs';
import { PageWrapper } from '../shared/page-wrapper.mjs';
import { EmptyState } from '../shared/empty-state.mjs';

function BoardPage({ boardId }) {
  const { data: board, error, refetch, isFetching } = useSuspenseBoard(boardId);
  if (error && !isFetching) {
    throw error;
  }
  const { Link: OverrideLink, navigate: overrideNavigate } = usePluginOverrides("kanban");
  const navigate = overrideNavigate || ((path) => {
    window.location.href = path;
  });
  const Link = OverrideLink || "a";
  const { deleteBoard, isDeleting } = useBoardMutations();
  const { deleteColumn, reorderColumns } = useColumnMutations();
  const { deleteTask, moveTask, reorderTasks } = useTaskMutations();
  const [modalState, setModalState] = useState({ type: "none" });
  const computeKanbanData = useCallback(
    (columns) => {
      if (!columns) return {};
      return columns.reduce(
        (acc, column) => {
          acc[column.id] = column.tasks || [];
          return acc;
        },
        {}
      );
    },
    []
  );
  const [kanbanState, setKanbanState] = useState(() => computeKanbanData(board?.columns));
  const serverKanbanData = useMemo(
    () => computeKanbanData(board?.columns),
    [board?.columns, computeKanbanData]
  );
  useEffect(() => {
    setKanbanState(serverKanbanData);
  }, [serverKanbanData]);
  const closeModal = useCallback(() => {
    setModalState({ type: "none" });
  }, []);
  const handleDeleteBoard = useCallback(async () => {
    try {
      await deleteBoard(boardId);
      closeModal();
      navigate("/pages/kanban");
      if (typeof window !== "undefined") {
        setTimeout(() => {
          if (window.location.pathname.includes(boardId)) {
            window.location.href = "/pages/kanban";
          }
        }, 100);
      }
    } catch (error2) {
      const message = error2 instanceof Error ? error2.message : "Failed to delete board";
      toast.error(message);
    }
  }, [deleteBoard, boardId, navigate, closeModal]);
  const handleKanbanChange = useCallback(
    async (newData) => {
      if (!board) return;
      let previousState = {};
      setKanbanState((current) => {
        previousState = current;
        return newData;
      });
      try {
        const oldKeys = Object.keys(previousState);
        const newKeys = Object.keys(newData);
        const isColumnMove = oldKeys.length === newKeys.length && oldKeys.join("") !== newKeys.join("");
        if (isColumnMove) {
          await reorderColumns(board.id, newKeys);
        } else {
          const crossColumnMoves = [];
          const columnsToReorder = /* @__PURE__ */ new Map();
          const targetColumnsOfCrossMove = /* @__PURE__ */ new Set();
          for (const [columnId, tasks] of Object.entries(newData)) {
            const oldTasks = previousState[columnId] || [];
            let hasOrderChanges = false;
            for (let i = 0; i < tasks.length; i++) {
              const task = tasks[i];
              if (!task) continue;
              if (task.columnId !== columnId) {
                crossColumnMoves.push({
                  taskId: task.id,
                  targetColumnId: columnId,
                  targetOrder: i
                });
                targetColumnsOfCrossMove.add(columnId);
              } else if (task.order !== i) {
                hasOrderChanges = true;
              }
            }
            const newTaskIds = new Set(tasks.map((t) => t.id));
            const tasksRemoved = oldTasks.some((t) => !newTaskIds.has(t.id));
            if (hasOrderChanges && !targetColumnsOfCrossMove.has(columnId) && !tasksRemoved) {
              columnsToReorder.set(
                columnId,
                tasks.map((t) => t.id)
              );
            }
          }
          for (const move of crossColumnMoves) {
            await moveTask(move.taskId, move.targetColumnId, move.targetOrder);
          }
          for (const [columnId, taskIds] of columnsToReorder) {
            await reorderTasks(columnId, taskIds);
          }
          for (const targetColumnId of targetColumnsOfCrossMove) {
            const tasks = newData[targetColumnId];
            if (tasks) {
              await reorderTasks(
                targetColumnId,
                tasks.map((t) => t.id)
              );
            }
          }
        }
        refetch();
      } catch (error2) {
        refetch();
        throw error2;
      }
    },
    [board, reorderColumns, moveTask, reorderTasks, refetch]
  );
  const orderedColumns = useMemo(() => {
    if (!board?.columns) return [];
    const columnMap = new Map(board.columns.map((c) => [c.id, c]));
    return Object.keys(kanbanState).map((columnId) => {
      const column = columnMap.get(columnId);
      if (!column) return null;
      return {
        ...column,
        tasks: kanbanState[columnId] || []
      };
    }).filter(
      (c) => c !== null
    );
  }, [board?.columns, kanbanState]);
  if (!board) {
    return /* @__PURE__ */ jsx(
      EmptyState,
      {
        title: "Board not found",
        description: "The board you're looking for doesn't exist or you don't have access to it.",
        action: /* @__PURE__ */ jsxs(Button, { onClick: () => navigate("/pages/kanban"), children: [
          /* @__PURE__ */ jsx(ArrowLeft, { className: "mr-2 h-4 w-4" }),
          "Back to Boards"
        ] })
      }
    );
  }
  return /* @__PURE__ */ jsxs(
    PageWrapper,
    {
      "data-testid": "board-page",
      className: "flex flex-col items-center",
      children: [
        /* @__PURE__ */ jsxs("div", { className: "w-full flex items-center justify-between mb-8", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-4", children: [
            /* @__PURE__ */ jsx(
              Link,
              {
                href: "/pages/kanban",
                className: "text-muted-foreground hover:text-foreground",
                children: /* @__PURE__ */ jsx(ArrowLeft, { className: "h-5 w-5" })
              }
            ),
            /* @__PURE__ */ jsxs("div", { children: [
              /* @__PURE__ */ jsx("h1", { className: "text-3xl font-bold", "data-testid": "page-header", children: board.name }),
              board.description && /* @__PURE__ */ jsx("p", { className: "text-muted-foreground mt-1", children: board.description })
            ] })
          ] }),
          /* @__PURE__ */ jsxs(DropdownMenu, { children: [
            /* @__PURE__ */ jsx(DropdownMenuTrigger, { asChild: true, children: /* @__PURE__ */ jsxs(Button, { variant: "outline", children: [
              /* @__PURE__ */ jsx(Settings, { className: "mr-2 h-4 w-4" }),
              "Actions"
            ] }) }),
            /* @__PURE__ */ jsxs(DropdownMenuContent, { align: "end", children: [
              /* @__PURE__ */ jsxs(
                DropdownMenuItem,
                {
                  onClick: () => setModalState({ type: "addColumn" }),
                  children: [
                    /* @__PURE__ */ jsx(Plus, { className: "mr-2 h-4 w-4" }),
                    "Add Column"
                  ]
                }
              ),
              /* @__PURE__ */ jsxs(
                DropdownMenuItem,
                {
                  onClick: () => setModalState({ type: "editBoard" }),
                  children: [
                    /* @__PURE__ */ jsx(Pencil, { className: "mr-2 h-4 w-4" }),
                    "Edit Board"
                  ]
                }
              ),
              /* @__PURE__ */ jsx(DropdownMenuSeparator, {}),
              /* @__PURE__ */ jsxs(
                DropdownMenuItem,
                {
                  onClick: () => setModalState({ type: "deleteBoard" }),
                  className: "text-red-600 focus:text-red-600",
                  children: [
                    /* @__PURE__ */ jsx(Trash2, { className: "mr-2 h-4 w-4" }),
                    "Delete Board"
                  ]
                }
              )
            ] })
          ] })
        ] }),
        orderedColumns.length > 0 ? /* @__PURE__ */ jsx(
          KanbanBoard,
          {
            columns: orderedColumns,
            kanbanState,
            onKanbanChange: handleKanbanChange,
            onAddTask: (columnId) => setModalState({ type: "addTask", columnId }),
            onEditTask: (columnId, taskId) => setModalState({ type: "editTask", columnId, taskId }),
            onEditColumn: (columnId) => setModalState({ type: "editColumn", columnId }),
            onDeleteColumn: (columnId) => setModalState({ type: "deleteColumn", columnId })
          }
        ) : /* @__PURE__ */ jsx(
          EmptyState,
          {
            title: "No columns yet",
            description: "Create your first column to start organizing tasks.",
            action: /* @__PURE__ */ jsxs(Button, { onClick: () => setModalState({ type: "addColumn" }), children: [
              /* @__PURE__ */ jsx(Plus, { className: "mr-2 h-4 w-4" }),
              "Add Column"
            ] })
          }
        ),
        /* @__PURE__ */ jsx(
          Dialog,
          {
            open: modalState.type === "addColumn",
            onOpenChange: (open) => !open && closeModal(),
            children: /* @__PURE__ */ jsxs(DialogContent, { children: [
              /* @__PURE__ */ jsxs(DialogHeader, { children: [
                /* @__PURE__ */ jsx(DialogTitle, { children: "Add Column" }),
                /* @__PURE__ */ jsx(DialogDescription, { children: "Add a new column to this board." })
              ] }),
              /* @__PURE__ */ jsx(
                ColumnForm,
                {
                  boardId,
                  onClose: closeModal,
                  onSuccess: () => {
                    closeModal();
                    refetch();
                  }
                }
              )
            ] })
          }
        ),
        /* @__PURE__ */ jsx(
          Dialog,
          {
            open: modalState.type === "editColumn",
            onOpenChange: (open) => !open && closeModal(),
            children: /* @__PURE__ */ jsxs(DialogContent, { children: [
              /* @__PURE__ */ jsxs(DialogHeader, { children: [
                /* @__PURE__ */ jsx(DialogTitle, { children: "Edit Column" }),
                /* @__PURE__ */ jsx(DialogDescription, { children: "Update the column details." })
              ] }),
              modalState.type === "editColumn" && /* @__PURE__ */ jsx(
                ColumnForm,
                {
                  boardId,
                  columnId: modalState.columnId,
                  column: board.columns?.find((c) => c.id === modalState.columnId),
                  onClose: closeModal,
                  onSuccess: () => {
                    closeModal();
                    refetch();
                  }
                }
              )
            ] })
          }
        ),
        /* @__PURE__ */ jsx(
          AlertDialog,
          {
            open: modalState.type === "deleteColumn",
            onOpenChange: (open) => !open && closeModal(),
            children: /* @__PURE__ */ jsxs(AlertDialogContent, { children: [
              /* @__PURE__ */ jsxs(AlertDialogHeader, { children: [
                /* @__PURE__ */ jsx(AlertDialogTitle, { children: "Delete Column" }),
                /* @__PURE__ */ jsx(AlertDialogDescription, { children: "Are you sure you want to delete this column? All tasks in this column will be permanently removed." })
              ] }),
              /* @__PURE__ */ jsxs(AlertDialogFooter, { children: [
                /* @__PURE__ */ jsx(AlertDialogCancel, { children: "Cancel" }),
                /* @__PURE__ */ jsx(
                  AlertDialogAction,
                  {
                    onClick: async () => {
                      if (modalState.type === "deleteColumn") {
                        try {
                          await deleteColumn(modalState.columnId);
                          closeModal();
                          refetch();
                        } catch (error2) {
                          const message = error2 instanceof Error ? error2.message : "Failed to delete column";
                          toast.error(message);
                        }
                      }
                    },
                    className: "bg-red-600 hover:bg-red-700",
                    children: "Delete"
                  }
                )
              ] })
            ] })
          }
        ),
        /* @__PURE__ */ jsx(
          Dialog,
          {
            open: modalState.type === "editBoard",
            onOpenChange: (open) => !open && closeModal(),
            children: /* @__PURE__ */ jsxs(DialogContent, { children: [
              /* @__PURE__ */ jsxs(DialogHeader, { children: [
                /* @__PURE__ */ jsx(DialogTitle, { children: "Edit Board" }),
                /* @__PURE__ */ jsx(DialogDescription, { children: "Update board details." })
              ] }),
              /* @__PURE__ */ jsx(
                BoardForm,
                {
                  board,
                  onClose: closeModal,
                  onSuccess: () => {
                    closeModal();
                    refetch();
                  }
                }
              )
            ] })
          }
        ),
        /* @__PURE__ */ jsx(
          AlertDialog,
          {
            open: modalState.type === "deleteBoard",
            onOpenChange: (open) => !open && closeModal(),
            children: /* @__PURE__ */ jsxs(AlertDialogContent, { children: [
              /* @__PURE__ */ jsxs(AlertDialogHeader, { children: [
                /* @__PURE__ */ jsx(AlertDialogTitle, { children: "Delete Board" }),
                /* @__PURE__ */ jsx(AlertDialogDescription, { children: "Are you sure you want to delete this board? This action cannot be undone. All columns and tasks will be permanently removed." })
              ] }),
              /* @__PURE__ */ jsxs(AlertDialogFooter, { children: [
                /* @__PURE__ */ jsx(AlertDialogCancel, { children: "Cancel" }),
                /* @__PURE__ */ jsx(
                  Button,
                  {
                    onClick: handleDeleteBoard,
                    disabled: isDeleting,
                    className: "bg-red-600 hover:bg-red-700",
                    children: isDeleting ? "Deleting..." : "Delete"
                  }
                )
              ] })
            ] })
          }
        ),
        /* @__PURE__ */ jsx(
          Dialog,
          {
            open: modalState.type === "addTask",
            onOpenChange: (open) => !open && closeModal(),
            children: /* @__PURE__ */ jsxs(DialogContent, { className: "max-w-3xl! max-h-screen overflow-y-auto", children: [
              /* @__PURE__ */ jsxs(DialogHeader, { children: [
                /* @__PURE__ */ jsx(DialogTitle, { children: "Add Task" }),
                /* @__PURE__ */ jsx(DialogDescription, { children: "Create a new task." })
              ] }),
              modalState.type === "addTask" && /* @__PURE__ */ jsx(
                TaskForm,
                {
                  columnId: modalState.columnId,
                  boardId,
                  columns: board.columns || [],
                  onClose: closeModal,
                  onSuccess: () => {
                    closeModal();
                    refetch();
                  }
                }
              )
            ] })
          }
        ),
        /* @__PURE__ */ jsx(
          Dialog,
          {
            open: modalState.type === "editTask",
            onOpenChange: (open) => !open && closeModal(),
            children: /* @__PURE__ */ jsxs(DialogContent, { className: "max-w-3xl! max-h-screen overflow-y-auto", children: [
              /* @__PURE__ */ jsxs(DialogHeader, { children: [
                /* @__PURE__ */ jsx(DialogTitle, { children: "Edit Task" }),
                /* @__PURE__ */ jsx(DialogDescription, { children: "Update task details." })
              ] }),
              modalState.type === "editTask" && /* @__PURE__ */ jsx(
                TaskForm,
                {
                  columnId: modalState.columnId,
                  boardId,
                  taskId: modalState.taskId,
                  task: board.columns?.find((c) => c.id === modalState.columnId)?.tasks?.find((t) => t.id === modalState.taskId),
                  columns: board.columns || [],
                  onClose: closeModal,
                  onSuccess: () => {
                    closeModal();
                    refetch();
                  },
                  onDelete: async () => {
                    try {
                      await deleteTask(modalState.taskId);
                      closeModal();
                      refetch();
                    } catch (error2) {
                      const message = error2 instanceof Error ? error2.message : "Failed to delete task";
                      toast.error(message);
                    }
                  }
                }
              )
            ] })
          }
        )
      ]
    }
  );
}

export { BoardPage };
