"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Avatar } from "@/components/ui/Avatar";
import { Icon } from "@/components/ui/Icon";
import { Swatches, PALETTE } from "@/components/ui/Swatches";
import { confirmDialog, promptDialog, alertDialog } from "@/components/ui/Dialog";
import {
  moveTaskAction,
  createColumnAction,
  renameColumnAction,
  deleteColumnAction,
  setColumnColorAction,
  createBoardAction,
  deleteBoardAction,
  updateBoardAction,
  setBoardAdminAction,
  createLabelAction,
  deleteLabelAction,
} from "@/lib/kanban/actions";
import { TaskDrawer, type BoardOptions } from "./TaskDrawer";
import type { BoardDTO, BoardListItem, ColumnDTO, TaskDTO } from "@/lib/kanban/queries";

const MAX_COLUMNS = 5;

// Auswählbare Board-Symbole (müssen in Icon.tsx existieren).
const BOARD_ICONS = ["kanban", "projects", "calendar", "creators", "chat", "meetings", "time", "shield", "pin", "hash"];

function fmtDate(iso: string): { text: string; past: boolean } {
  const d = new Date(iso);
  return {
    text: d.toLocaleDateString("de-DE", { day: "2-digit", month: "2-digit" }),
    past: d.getTime() < Date.now() - 86400000,
  };
}

type DrawerState =
  | { mode: "create"; columnId: string }
  | { mode: "edit"; task: TaskDTO }
  | null;

export function KanbanBoard({
  board,
  boards,
  options,
  canUse,
  canComment,
  canCreateBoard,
  canManageBoard,
  currentUserId,
}: {
  board: BoardDTO;
  boards: BoardListItem[];
  options: BoardOptions;
  canUse: boolean;
  canComment: boolean;
  canCreateBoard: boolean;
  canManageBoard: boolean;
  currentUserId: string;
}) {
  const router = useRouter();
  const [columns, setColumns] = useState<ColumnDTO[]>(board.columns);
  const [drawer, setDrawer] = useState<DrawerState>(null);
  const [draggingId, setDraggingId] = useState<string | null>(null);
  const [overCol, setOverCol] = useState<string | null>(null);
  const [colorForCol, setColorForCol] = useState<string | null>(null);
  const [boardSettings, setBoardSettings] = useState(false);
  const [meta, setMeta] = useState({ name: board.name, icon: board.icon });
  const [adminId, setAdminId] = useState<string>(board.adminId ?? "");
  const [labels, setLabels] = useState(options.labels);

  // Board-Wechsel: State DURING render angleichen (kein Flackern/Spalten-Springen).
  const [renderedBoardId, setRenderedBoardId] = useState(board.id);
  if (renderedBoardId !== board.id) {
    setRenderedBoardId(board.id);
    setColumns(board.columns);
    setMeta({ name: board.name, icon: board.icon });
    setAdminId(board.adminId ?? "");
    setLabels(options.labels);
    setBoardSettings(false);
    setColorForCol(null);
  }

  const boardIcon = meta.icon || "kanban";
  const isDefault = boards.find((b) => b.id === board.id)?.isDefault;

  // ── Board-Wechsel / CRUD ──
  const gotoBoard = (id: string) => {
    const def = boards.find((b) => b.id === id)?.isDefault;
    router.push(def ? "/kanban" : `/kanban?board=${id}`);
  };
  const addBoard = async () => {
    const name = await promptDialog({ title: "Neues Board", placeholder: "Board-Name", confirmLabel: "Erstellen" });
    if (!name) return;
    const res = await createBoardAction(name);
    if (res.id) router.push(`/kanban?board=${res.id}`);
    else if (res.error) await alertDialog({ title: "Fehler", message: res.error, danger: true });
  };
  const removeBoard = async () => {
    if (
      !(await confirmDialog({
        title: "Board löschen?",
        message: `„${meta.name}“ und alle enthaltenen Aufgaben werden dauerhaft entfernt.`,
        danger: true,
      }))
    )
      return;
    const res = await deleteBoardAction(board.id);
    if (res.error) await alertDialog({ title: "Nicht möglich", message: res.error, danger: true });
    else router.push("/kanban");
  };
  const saveMeta = async (patch: Partial<typeof meta>) => {
    setMeta((m) => ({ ...m, ...patch }));
    await updateBoardAction(board.id, patch);
    router.refresh();
  };
  const renameBoard = async () => {
    const name = await promptDialog({ title: "Board umbenennen", defaultValue: meta.name, confirmLabel: "Speichern" });
    if (name) void saveMeta({ name });
  };
  const changeAdmin = async (userId: string) => {
    setAdminId(userId);
    await setBoardAdminAction(board.id, userId || null);
    router.refresh();
  };

  // ── Labels (nur Board-Admin) ──
  const addLabel = async () => {
    const name = await promptDialog({ title: "Neues Label", placeholder: "Label-Name", confirmLabel: "Erstellen" });
    if (!name) return;
    const res = await createLabelAction(name, PALETTE[labels.length % PALETTE.length], board.id);
    if (res.error) return alertDialog({ title: "Fehler", message: res.error, danger: true });
    if (res.label) {
      setLabels((l) => [...l, res.label!]);
      router.refresh();
    }
  };
  const removeLabel = async (id: string) => {
    if (!(await confirmDialog({ title: "Label löschen?", message: "Das Label wird von allen Aufgaben entfernt.", danger: true }))) return;
    setLabels((l) => l.filter((x) => x.id !== id));
    await deleteLabelAction(id, board.id);
    router.refresh();
  };

  // ── Spalten CRUD (nur Board-Admin) ──
  const addColumn = async () => {
    const name = await promptDialog({ title: "Neue Spalte", defaultValue: "Neue Spalte", confirmLabel: "Erstellen" });
    if (name === null) return;
    const res = await createColumnAction(board.id, name);
    if (res.column) {
      setColumns((c) => [...c, res.column!]);
      router.refresh();
    } else if (res.error) await alertDialog({ title: "Fehler", message: res.error, danger: true });
  };
  const renameColumn = async (col: ColumnDTO) => {
    const name = await promptDialog({ title: "Spalte umbenennen", defaultValue: col.name, confirmLabel: "Speichern" });
    if (!name) return;
    setColumns((c) => c.map((x) => (x.id === col.id ? { ...x, name } : x)));
    await renameColumnAction(col.id, name);
    router.refresh();
  };
  const removeColumn = async (col: ColumnDTO) => {
    if (
      !(await confirmDialog({
        title: "Spalte löschen?",
        message: `„${col.name}“ inklusive aller Aufgaben wird entfernt.`,
        danger: true,
      }))
    )
      return;
    setColumns((c) => c.filter((x) => x.id !== col.id));
    await deleteColumnAction(col.id);
    router.refresh();
  };
  const setColumnColor = (col: ColumnDTO, color: string | null) => {
    const c = color ?? "#9ed7ff";
    setColumns((cs) => cs.map((x) => (x.id === col.id ? { ...x, color: c } : x)));
    setColorForCol(null);
    void setColumnColorAction(col.id, c).then(() => router.refresh());
  };

  // ── Drag & Drop (Benutzung) ──
  const drop = (toColumnId: string, beforeTaskId: string | null) => {
    const taskId = draggingId;
    setDraggingId(null);
    setOverCol(null);
    if (!taskId || !canUse) return;
    const next = columns.map((c) => ({ ...c, tasks: [...c.tasks] }));
    let moved: TaskDTO | undefined;
    for (const c of next) {
      const i = c.tasks.findIndex((t) => t.id === taskId);
      if (i >= 0) {
        moved = c.tasks.splice(i, 1)[0];
        break;
      }
    }
    if (!moved) return;
    moved = { ...moved, columnId: toColumnId };
    const target = next.find((c) => c.id === toColumnId)!;
    if (beforeTaskId && beforeTaskId !== taskId) {
      const idx = target.tasks.findIndex((t) => t.id === beforeTaskId);
      target.tasks.splice(idx < 0 ? target.tasks.length : idx, 0, moved);
    } else {
      target.tasks.push(moved);
    }
    setColumns(next);
    void moveTaskAction(taskId, toColumnId, target.tasks.map((t) => t.id));
  };

  const onSaved = (task: TaskDTO, mode: "create" | "edit") => {
    setColumns((prev) =>
      prev.map((c) => {
        let tasks = c.tasks.filter((t) => t.id !== task.id);
        if (c.id === task.columnId) {
          tasks = mode === "create" ? [...tasks, task] : [...tasks, task].sort((a, b) => a.position - b.position);
        }
        return { ...c, tasks };
      }),
    );
    setDrawer(null);
    router.refresh();
  };
  const onDeleted = (id: string) => {
    setColumns((prev) => prev.map((c) => ({ ...c, tasks: c.tasks.filter((t) => t.id !== id) })));
    setDrawer(null);
    router.refresh();
  };

  return (
    <div className="flex flex-col gap-4">
      {/* Board-Wechsler: Boards deutlich abgesetzt von den Aktionen */}
      <div className="board-bar" data-reveal>
        <div className="board-switcher">
          {boards.map((b) => (
            <button
              key={b.id}
              className="board-pill"
              data-active={b.id === board.id}
              onClick={() => gotoBoard(b.id)}
            >
              <Icon name={b.icon || "kanban"} size={15} />
              <span className="truncate">{b.name}</span>
            </button>
          ))}
        </div>

        {canCreateBoard || canManageBoard ? (
          <div className="board-actions">
            {canCreateBoard ? (
              <button className="board-action-btn" onClick={addBoard} title="Neues Board">
                <Icon name="plus" size={15} /> Board
              </button>
            ) : null}
            {canManageBoard ? (
              <button className="board-action-btn" onClick={() => setBoardSettings(true)} title="Board anpassen">
                <Icon name="settings" size={15} /> Anpassen
              </button>
            ) : null}
          </div>
        ) : null}
      </div>

      {board.adminName && !canManageBoard ? (
        <div className="text-muted text-xs" data-reveal>
          Board-Admin: <span className="font-bold">{board.adminName}</span> · du kannst Aufgaben nutzen
        </div>
      ) : null}

      {/* Board-Einstellungen (nur Board-Admin) */}
      {boardSettings && canManageBoard ? (
        <div className="dialog-overlay" onMouseDown={(e) => e.target === e.currentTarget && setBoardSettings(false)}>
          <div className="dialog-card animate-in" role="dialog" aria-modal="true">
            <div className="mb-4 flex items-center justify-between">
              <h3>Board anpassen</h3>
              <button className="btn btn-ghost btn-sm" onClick={() => setBoardSettings(false)} aria-label="Schließen">
                <Icon name="close" size={16} />
              </button>
            </div>

            <div className="field">
              <label className="label">Name</label>
              <div className="flex items-center gap-2">
                <div className="board-name-preview">
                  <Icon name={boardIcon} size={16} /> {meta.name}
                </div>
                <button className="btn btn-ghost btn-sm" onClick={renameBoard}>
                  <Icon name="settings" size={14} /> Umbenennen
                </button>
              </div>
            </div>

            <div className="field mt-4">
              <label className="label">Symbol</label>
              <div className="flex flex-wrap gap-1.5">
                {BOARD_ICONS.map((ic) => (
                  <button
                    key={ic}
                    type="button"
                    className="icon-pick"
                    data-active={boardIcon === ic}
                    onClick={() => saveMeta({ icon: ic })}
                    title={ic}
                  >
                    <Icon name={ic} size={17} />
                  </button>
                ))}
              </div>
            </div>

            <div className="field mt-4">
              <label className="label">Board-Admin</label>
              <select className="select" value={adminId} onChange={(e) => changeAdmin(e.target.value)}>
                <option value="">— Niemand (nur System-Admins) —</option>
                {options.users.map((u) => (
                  <option key={u.id} value={u.id}>{u.name}</option>
                ))}
              </select>
              <p className="text-muted mt-1 text-xs">
                Der Board-Admin verwaltet Spalten, Labels, Farben und Einstellungen.
              </p>
            </div>

            <div className="field mt-4">
              <div className="flex items-center justify-between">
                <label className="label">Labels</label>
                <button className="pill btn-sm" type="button" onClick={addLabel}>
                  <Icon name="plus" size={14} /> Label
                </button>
              </div>
              {labels.length === 0 ? (
                <p className="text-muted text-sm">Noch keine Labels.</p>
              ) : (
                <div className="flex flex-wrap gap-2">
                  {labels.map((l) => (
                    <span key={l.id} className="label-chip label-chip-editable" style={{ borderColor: `${l.color}66`, background: `${l.color}18`, color: "#fff" }}>
                      <span className="inline-flex items-center gap-1.5">
                        <span className="label-dot" style={{ background: l.color }} />
                        {l.name}
                      </span>
                      <button type="button" className="label-x" onClick={() => removeLabel(l.id)} aria-label="Label löschen">
                        <Icon name="close" size={11} />
                      </button>
                    </span>
                  ))}
                </div>
              )}
            </div>

            <div className="form-footer">
              {!isDefault ? (
                <button className="btn btn-danger btn-sm" onClick={removeBoard}>
                  <Icon name="trash" size={14} /> Board löschen
                </button>
              ) : (
                <span className="text-muted text-xs">Standard-Board</span>
              )}
              <button className="btn btn-primary btn-sm" onClick={() => setBoardSettings(false)}>
                Fertig
              </button>
            </div>
          </div>
        </div>
      ) : null}

      {/* Board */}
      <div className="kanban-grid" data-reveal>
        {columns.map((col) => {
          const dot = col.color ?? "var(--blue)";
          return (
            <div key={col.id} className="kanban-col">
              <div className="kanban-col-head">
                {canManageBoard ? (
                  <div className="relative">
                    <button
                      className="kanban-col-dot-btn"
                      style={{ background: dot }}
                      onClick={() => setColorForCol((c) => (c === col.id ? null : col.id))}
                      title="Spaltenfarbe"
                    />
                    {colorForCol === col.id ? (
                      <>
                        <div className="pop-backdrop" onClick={() => setColorForCol(null)} />
                        <div className="card-sm pop-solid col-color-pop">
                          <Swatches value={col.color} onChange={(color) => setColumnColor(col, color)} />
                        </div>
                      </>
                    ) : null}
                  </div>
                ) : (
                  <span className="kanban-col-dot" style={{ background: dot }} />
                )}
                <span className="truncate font-bold">{col.name}</span>
                <span className="badge ml-auto">{col.tasks.length}</span>
                {canUse ? (
                  <button className="icon-btn" style={{ width: 26, height: 26 }} onClick={() => setDrawer({ mode: "create", columnId: col.id })} title="Aufgabe hinzufügen">
                    <Icon name="plus" size={15} />
                  </button>
                ) : null}
                {canManageBoard ? (
                  <>
                    <button className="icon-btn" style={{ width: 26, height: 26 }} onClick={() => renameColumn(col)} title="Umbenennen">
                      <Icon name="settings" size={14} />
                    </button>
                    <button className="icon-btn" style={{ width: 26, height: 26 }} onClick={() => removeColumn(col)} title="Spalte löschen">
                      <Icon name="trash" size={14} />
                    </button>
                  </>
                ) : null}
              </div>

              <div
                className={`kanban-col-body ${overCol === col.id ? "is-over" : ""}`}
                onDragOver={(e) => {
                  if (!draggingId) return;
                  e.preventDefault();
                  setOverCol(col.id);
                }}
                onDragLeave={() => setOverCol((c) => (c === col.id ? null : c))}
                onDrop={(e) => {
                  e.preventDefault();
                  drop(col.id, null);
                }}
              >
                {col.tasks.map((t) => {
                  const dl = t.deadline ? fmtDate(t.deadline) : null;
                  return (
                    <div
                      key={t.id}
                      className={`task-card ${draggingId === t.id ? "is-dragging" : ""}`}
                      draggable={canUse}
                      style={
                        t.color
                          ? { borderLeft: `3px solid ${t.color}`, background: `linear-gradient(100deg, ${t.color}1c, transparent 60%), var(--panel2)` }
                          : undefined
                      }
                      onDragStart={() => setDraggingId(t.id)}
                      onDragEnd={() => setDraggingId(null)}
                      onDragOver={(e) => {
                        if (!draggingId) return;
                        e.preventDefault();
                        e.stopPropagation();
                        setOverCol(col.id);
                      }}
                      onDrop={(e) => {
                        e.preventDefault();
                        e.stopPropagation();
                        drop(col.id, t.id);
                      }}
                      onClick={() => setDrawer({ mode: "edit", task: t })}
                    >
                      {t.labels.length > 0 ? (
                        <div className="mb-2 flex flex-wrap gap-1">
                          {t.labels.map((l) => (
                            <span key={l.id} className="label-chip" style={{ borderColor: l.color, color: "#fff", background: `${l.color}22` }}>
                              {l.name}
                            </span>
                          ))}
                        </div>
                      ) : null}

                      <div className="font-bold leading-snug">{t.title}</div>

                      {t.projectName ? <div className="mt-1 text-xs text-muted">{t.projectName}</div> : null}

                      <div className="mt-3 flex items-center justify-between">
                        <div className="flex items-center gap-2 text-xs text-muted">
                          {dl ? (
                            <span className="inline-flex items-center gap-1" style={{ color: dl.past ? "var(--pink)" : undefined }}>
                              <Icon name="calendar" size={13} /> {dl.text}
                            </span>
                          ) : null}
                          {t.checklist.total > 0 ? (
                            <span className="inline-flex items-center gap-1">
                              <Icon name="check" size={13} /> {t.checklist.done}/{t.checklist.total}
                            </span>
                          ) : null}
                          {t.commentCount > 0 ? (
                            <span className="inline-flex items-center gap-1">
                              <Icon name="chat" size={13} /> {t.commentCount}
                            </span>
                          ) : null}
                        </div>
                        {t.assignees.length > 0 ? (
                          <div className="assignee-stack">
                            {t.assignees.slice(0, 3).map((a) => (
                              <Avatar key={a.id} name={a.name} src={a.avatarUrl} size={24} />
                            ))}
                            {t.assignees.length > 3 ? (
                              <span className="badge" style={{ marginLeft: -8 }}>+{t.assignees.length - 3}</span>
                            ) : null}
                          </div>
                        ) : null}
                      </div>
                    </div>
                  );
                })}

                {col.tasks.length === 0 ? <p className="text-muted px-1 py-3 text-center text-xs">Keine Aufgaben</p> : null}
              </div>
            </div>
          );
        })}

        {canManageBoard && columns.length < MAX_COLUMNS ? (
          <button className="kanban-addcol" onClick={addColumn}>
            <span className="flex flex-col items-center gap-1">
              <Icon name="plus" size={20} />
              <span className="text-sm font-bold">Spalte hinzufügen</span>
              <span className="text-xs text-muted">{columns.length}/{MAX_COLUMNS}</span>
            </span>
          </button>
        ) : null}
      </div>

      {drawer ? (
        <TaskDrawer
          mode={drawer.mode}
          boardId={board.id}
          columnId={drawer.mode === "create" ? drawer.columnId : undefined}
          task={drawer.mode === "edit" ? drawer.task : undefined}
          options={{ ...options, labels }}
          canUse={canUse}
          canComment={canComment}
          canManageBoard={canManageBoard}
          currentUserId={currentUserId}
          onClose={() => setDrawer(null)}
          onSaved={onSaved}
          onDeleted={onDeleted}
        />
      ) : null}
    </div>
  );
}
