"use client";

/**
 * Kanban pipeline board — columns for each content pipeline stage.
 * Drag cards between columns to update pipelineStage.
 */

import { DndContext, PointerSensor, useSensor, useSensors, type DragEndEvent } from "@dnd-kit/core";
import { useDraggable, useDroppable } from "@dnd-kit/core";
import { FileText, Calendar, User, GripVertical } from "lucide-react";

interface Task { id: string; title: string; pipelineStage: string | null; contentType: string | null; targetKeyword: string | null; priority: string; dueDate: string | null; assignedTo: string | null; status: string }

const STAGES = [
  { id: "idea", label: "Idea", color: "border-t-slate-400" },
  { id: "brief_created", label: "Brief", color: "border-t-blue-400" },
  { id: "writing", label: "Writing", color: "border-t-violet-400" },
  { id: "editing", label: "Editing", color: "border-t-amber-400" },
  { id: "review", label: "Review", color: "border-t-orange-400" },
  { id: "approved", label: "Approved", color: "border-t-emerald-400" },
  { id: "published", label: "Published", color: "border-t-green-500" },
];

const PRIORITY_DOT: Record<string, string> = { critical: "bg-red-500", high: "bg-orange-500", medium: "bg-blue-500", low: "bg-slate-400" };
const TYPE_LABEL: Record<string, string> = { blog_post: "Blog", landing_page: "Landing", service_page: "Service", case_study: "Case Study", social_post: "Social" };

interface Props { pipeline: Record<string, Task[]>; onStageChange: (taskId: string, stage: string) => void; onClickTask: (id: string) => void }

export default function PipelineBoard({ pipeline, onStageChange, onClickTask }: Props) {
  const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 5 } }));

  function handleDragEnd(e: DragEndEvent) {
    if (!e.over) return;
    onStageChange(String(e.active.id), String(e.over.id));
  }

  return (
    <DndContext sensors={sensors} onDragEnd={handleDragEnd}>
      <div className="flex gap-3 overflow-x-auto pb-4">
        {STAGES.map((stage) => {
          const tasks = pipeline[stage.id] || [];
          return <StageColumn key={stage.id} stage={stage} tasks={tasks} onClickTask={onClickTask} />;
        })}
      </div>
    </DndContext>
  );
}

function StageColumn({ stage, tasks, onClickTask }: { stage: typeof STAGES[0]; tasks: Task[]; onClickTask: (id: string) => void }) {
  const { setNodeRef, isOver } = useDroppable({ id: stage.id });
  return (
    <div ref={setNodeRef} className={`w-56 shrink-0 rounded-xl border border-slate-200 border-t-4 ${stage.color} ${isOver ? "bg-brand-50/30" : "bg-slate-50/50"}`}>
      <div className="px-3 py-2.5 flex items-center justify-between">
        <span className="text-xs font-bold text-slate-700">{stage.label}</span>
        <span className="text-[10px] text-slate-400 font-bold tabular-nums">{tasks.length}</span>
      </div>
      <div className="px-2 pb-2 space-y-1.5 min-h-[100px]">
        {tasks.map((t) => <TaskCard key={t.id} task={t} onClick={() => onClickTask(t.id)} />)}
      </div>
    </div>
  );
}

function TaskCard({ task, onClick }: { task: Task; onClick: () => void }) {
  const { attributes, listeners, setNodeRef, transform, isDragging } = useDraggable({ id: task.id });
  const style = transform ? { transform: `translate(${transform.x}px, ${transform.y}px)`, opacity: isDragging ? 0.5 : 1, zIndex: 50 } : undefined;
  return (
    <div ref={setNodeRef} style={style} onClick={onClick} className="bg-white rounded-lg border border-slate-200 px-3 py-2.5 cursor-pointer hover:shadow-sm">
      <div {...attributes} {...listeners} className="float-right cursor-grab text-slate-300 hover:text-slate-500"><GripVertical className="w-3 h-3" /></div>
      <div className="flex items-center gap-1.5 mb-1">
        <span className={`w-2 h-2 rounded-full ${PRIORITY_DOT[task.priority] || PRIORITY_DOT.medium}`} />
        <span className="text-xs font-semibold text-slate-900 truncate">{task.title}</span>
      </div>
      {task.targetKeyword && <p className="text-[10px] text-brand-600 font-medium truncate mb-1">{task.targetKeyword}</p>}
      <div className="flex items-center gap-2 text-[10px] text-slate-400">
        {task.contentType && <span className="bg-slate-100 rounded px-1.5 py-0.5 font-semibold">{TYPE_LABEL[task.contentType] || task.contentType}</span>}
        {task.dueDate && <span className="flex items-center gap-0.5"><Calendar className="w-2.5 h-2.5" />{new Date(task.dueDate).toLocaleDateString("en-US", { month: "short", day: "numeric" })}</span>}
        {task.assignedTo && <User className="w-2.5 h-2.5 ml-auto" />}
      </div>
    </div>
  );
}
