"use client";

import { useOptimistic, useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { reorderSessions } from "@/app/dashboard/c/[id]/actions";

export type BoardSession = {
  id: string;
  title: string;
  type: string;
  typeCls: string;
  start: string; // pre-formatted
  end: string;
  durationMin: number;
  trackName?: string;
  trackColor?: string;
  speakers: string[];
  mode: string;
};

export type BoardLane = {
  key: string; // roomId or "none"
  title: string;
  sub?: string; // venue · capacity
  sessions: BoardSession[];
};

export function AgendaBoard({ confId, day, lanes }: { confId: string; day: string; lanes: BoardLane[] }) {
  return (
    <div className="space-y-6">
      {lanes.map((lane) => (
        <Lane key={`${day}-${lane.key}`} confId={confId} day={day} lane={lane} />
      ))}
    </div>
  );
}

function Lane({ confId, day, lane }: { confId: string; day: string; lane: BoardLane }) {
  const router = useRouter();
  const [isPending, startTransition] = useTransition();
  const [order, setOrder] = useState(lane.sessions.map((s) => s.id));
  const [optimisticOrder, setOptimisticOrder] = useOptimistic(order);
  const [dragId, setDragId] = useState<string | null>(null);
  const [overId, setOverId] = useState<string | null>(null);

  const byId = new Map(lane.sessions.map((s) => [s.id, s]));
  const ids = optimisticOrder.filter((id) => byId.has(id));

  const commit = (next: string[]) => {
    startTransition(async () => {
      setOptimisticOrder(next);
      setOrder(next);
      await reorderSessions(confId, day, lane.key, next);
      router.refresh();
    });
  };

  const move = (id: string, dir: -1 | 1) => {
    const i = ids.indexOf(id);
    const j = i + dir;
    if (i < 0 || j < 0 || j >= ids.length) return;
    const next = [...ids];
    [next[i], next[j]] = [next[j], next[i]];
    commit(next);
  };

  const dropOn = (targetId: string) => {
    if (!dragId || dragId === targetId) return;
    const next = ids.filter((x) => x !== dragId);
    next.splice(next.indexOf(targetId) + (ids.indexOf(dragId) < ids.indexOf(targetId) ? 1 : 0), 0, dragId);
    commit(next);
  };

  return (
    <section className={isPending ? "opacity-60 transition" : "transition"}>
      <div className="mb-2 flex items-baseline gap-2">
        <h3 className="text-sm font-bold text-zinc-200">🚪 {lane.title}</h3>
        {lane.sub && <span className="text-xs text-zinc-500">{lane.sub}</span>}
        <span className="ml-auto text-[11px] text-zinc-600">drag to reorder — times reflow automatically</span>
      </div>
      <div className="space-y-2">
        {ids.map((id, idx) => {
          const s = byId.get(id)!;
          return (
            <div
              key={id}
              draggable
              onDragStart={(e) => { setDragId(id); e.dataTransfer.effectAllowed = "move"; }}
              onDragEnd={() => { setDragId(null); setOverId(null); }}
              onDragOver={(e) => { e.preventDefault(); setOverId(id); }}
              onDrop={(e) => { e.preventDefault(); dropOn(id); setDragId(null); setOverId(null); }}
              className={`group flex cursor-grab items-start gap-3 rounded-xl border bg-white/60 p-3.5 shadow-sm backdrop-blur transition active:cursor-grabbing ${
                overId === id && dragId && dragId !== id
                  ? "border-indigo-400 ring-2 ring-indigo-400/30"
                  : dragId === id
                  ? "border-indigo-300 opacity-50"
                  : "border-white/70"
              }`}
            >
              <span className="mt-1 select-none text-zinc-400" title="Drag handle">⠿</span>
              <div className="w-24 shrink-0 pt-0.5 text-sm tabular-nums">
                <div className="font-bold text-zinc-200">{s.start}</div>
                <div className="text-xs text-zinc-500">{s.end} · {s.durationMin}m</div>
              </div>
              <div className="min-w-0 flex-1">
                <div className="flex flex-wrap items-center gap-2 text-[11px]">
                  <span className={`rounded-md border px-1.5 py-0.5 font-semibold ${s.typeCls}`}>{s.type}</span>
                  {s.trackName && <span className="font-medium" style={{ color: s.trackColor }}>{s.trackName}</span>}
                  {s.mode !== "PHYSICAL" && <span className="text-zinc-500">🖥️ {s.mode.toLowerCase()}</span>}
                </div>
                <div className="mt-1 truncate text-sm font-semibold text-zinc-100">{s.title}</div>
                {s.speakers.length > 0 && <div className="mt-0.5 truncate text-xs text-zinc-500">{s.speakers.join(", ")}</div>}
              </div>
              <div className="flex shrink-0 items-center gap-1 opacity-0 transition group-hover:opacity-100">
                <button onClick={() => move(id, -1)} disabled={idx === 0} className="rounded-md border border-white/70 bg-white/70 px-1.5 py-0.5 text-xs text-zinc-400 disabled:opacity-30" title="Move up">↑</button>
                <button onClick={() => move(id, 1)} disabled={idx === ids.length - 1} className="rounded-md border border-white/70 bg-white/70 px-1.5 py-0.5 text-xs text-zinc-400 disabled:opacity-30" title="Move down">↓</button>
                <Link href={`/dashboard/c/${confId}/agenda?day=${day}&edit=${id}`} className="rounded-md border border-white/70 bg-white/70 px-1.5 py-0.5 text-xs text-indigo-600" title="Edit session">✎</Link>
              </div>
            </div>
          );
        })}
      </div>
    </section>
  );
}
