import {
  DndContext,
  closestCorners,
  PointerSensor,
  TouchSensor,
  useSensor,
  useSensors,
  type DragEndEvent,
  useDroppable,
  useDraggable,
} from '@dnd-kit/core';
import { format, parseISO } from 'date-fns';
import type { ProjectTask } from '@/types';
import { Badge } from '@/components/ui/badge';

const COLUMNS: { id: string; label: string; color: string }[] = [
  { id: 'pending', label: 'Pending', color: 'text-gray-400' },
  { id: 'in_progress', label: 'In Progress', color: 'text-blue-400' },
  { id: 'blocked', label: 'Blocked', color: 'text-red-400' },
  { id: 'on_hold', label: 'On Hold', color: 'text-orange-400' },
  { id: 'review', label: 'Review', color: 'text-yellow-400' },
  { id: 'completed', label: 'Completed', color: 'text-green-400' },
];

const priorityColors: Record<string, string> = {
  none: 'bg-gray-500/20 text-gray-400',
  low: 'bg-green-500/20 text-green-400',
  medium: 'bg-yellow-500/20 text-yellow-400',
  high: 'bg-red-500/20 text-red-400',
};

interface KanbanBoardProps {
  tasks: ProjectTask[];
  selectedTaskId: number | null;
  kanbanParentTask?: ProjectTask | null;
  onSelectTask: (taskId: number) => void;
  onStatusChange: (taskId: number, status: string) => void;
  onBackToAllTasks?: () => void;
}

function KanbanColumn({
  column,
  tasks,
  selectedTaskId,
  onSelectTask,
}: {
  column: (typeof COLUMNS)[0];
  tasks: ProjectTask[];
  selectedTaskId: number | null;
  onSelectTask: (taskId: number) => void;
}) {
  const { setNodeRef, isOver } = useDroppable({ id: column.id });

  return (
    <div
      ref={setNodeRef}
      className={`flex-1 min-w-[160px] md:min-w-[200px] rounded-lg border transition-colors duration-150 ${
        isOver ? 'border-accent/40 bg-accent/5' : 'border-border bg-card/50'
      }`}
    >
      {/* Column header */}
      <div className="px-3 py-2.5 border-b border-border">
        <div className="flex items-center justify-between">
          <span className={`text-sm font-semibold font-heading ${column.color}`}>
            {column.label}
          </span>
          <span className="text-[11px] text-muted-foreground tabular-nums bg-secondary rounded-full px-2 py-0.5">
            {tasks.length}
          </span>
        </div>
      </div>

      {/* Cards */}
      <div className="p-2 space-y-2 min-h-[100px]">
        {tasks.map((task) => (
          <KanbanCard
            key={task.id}
            task={task}
            isSelected={selectedTaskId === task.id}
            onSelect={() => onSelectTask(task.id)}
          />
        ))}
      </div>
    </div>
  );
}

function KanbanCard({
  task,
  isSelected,
  onSelect,
}: {
  task: ProjectTask;
  isSelected: boolean;
  onSelect: () => void;
}) {
  const { attributes, listeners, setNodeRef, transform, isDragging } = useDraggable({
    id: task.id,
    data: { task },
  });

  const style = transform
    ? {
        transform: `translate(${transform.x}px, ${transform.y}px)`,
        opacity: isDragging ? 0.5 : 1,
      }
    : undefined;

  const completedSubtasks = task.subtasks?.filter((s) => s.status === 'completed').length ?? 0;
  const totalSubtasks = task.subtasks?.length ?? 0;

  return (
    <div
      ref={setNodeRef}
      style={style}
      {...listeners}
      {...attributes}
      onClick={onSelect}
      className={`rounded-md border p-3 cursor-pointer transition-all duration-150 ${
        isSelected
          ? 'border-accent/40 bg-accent/5 shadow-sm shadow-accent/10'
          : 'border-border bg-card hover:bg-card-elevated hover:border-accent/20'
      }`}
    >
      <p className="text-sm font-medium leading-tight mb-2">{task.title}</p>
      <div className="flex items-center gap-1.5 flex-wrap">
        <Badge
          className={`text-[9px] px-1.5 py-0.5 rounded-full ${priorityColors[task.priority] ?? priorityColors.none}`}
        >
          {task.priority}
        </Badge>
        {task.due_date && (
          <span className="text-[11px] text-muted-foreground tabular-nums">
            {format(parseISO(task.due_date), 'MMM d')}
          </span>
        )}
        {totalSubtasks > 0 && (
          <span className="text-[11px] text-muted-foreground tabular-nums">
            {completedSubtasks}/{totalSubtasks}
          </span>
        )}
      </div>
    </div>
  );
}

export default function KanbanBoard({
  tasks,
  selectedTaskId,
  kanbanParentTask,
  onSelectTask,
  onStatusChange,
  onBackToAllTasks,
}: KanbanBoardProps) {
  const sensors = useSensors(
    useSensor(PointerSensor, { activationConstraint: { distance: 5 } })
,
    useSensor(TouchSensor, { activationConstraint: { delay: 200, tolerance: 8 } })
  );

  // Subtask view is driven by kanbanParentTask (decoupled from selected task)
  const isSubtaskView = kanbanParentTask != null && (kanbanParentTask.subtasks?.length ?? 0) > 0;
  const activeTasks: ProjectTask[] = isSubtaskView ? (kanbanParentTask.subtasks ?? []) : tasks;

  const handleDragEnd = (event: DragEndEvent) => {
    const { active, over } = event;
    if (!over) return;

    const taskId = active.id as number;
    const newStatus = over.id as string;

    const task = activeTasks.find((t) => t.id === taskId);
    if (task && task.status !== newStatus && COLUMNS.some((c) => c.id === newStatus)) {
      onStatusChange(taskId, newStatus);
    }
  };

  const tasksByStatus = COLUMNS.map((col) => ({
    column: col,
    tasks: activeTasks.filter((t) => t.status === col.id),
  }));

  return (
    <div className="flex flex-col gap-3">
      {/* Subtask view header */}
      {isSubtaskView && kanbanParentTask && (
        <div className="flex items-center gap-3 px-1">
          <button
            onClick={onBackToAllTasks}
            className="text-xs text-muted-foreground hover:text-foreground transition-colors underline underline-offset-2"
          >
            Back to all tasks
          </button>
          <span className="text-muted-foreground text-xs">/</span>
          <span className="text-xs text-foreground font-medium">
            Subtasks of: {kanbanParentTask.title}
          </span>
        </div>
      )}

      <DndContext
        sensors={sensors}
        collisionDetection={closestCorners}
        onDragEnd={handleDragEnd}
      >
        <div className="flex gap-3 overflow-x-auto pb-2">
          {tasksByStatus.map(({ column, tasks: colTasks }) => (
            <KanbanColumn
              key={column.id}
              column={column}
              tasks={colTasks}
              selectedTaskId={selectedTaskId}
              onSelectTask={onSelectTask}
            />
          ))}
        </div>
      </DndContext>
    </div>
  );
}
