"use client";

import { useRef, useEffect } from "react";
import { useDraggable, useDroppable } from "@dnd-kit/core";
import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";
import { TaskCard } from "./task-card";
import type { KanbanColumn as KanbanColumnType } from "@/lib/api/tasks";

const COLUMN_COLORS: Record<string, string> = {
  overdue_tasks: "border-red-200 bg-red-50/40 dark:border-red-500/20 dark:bg-red-950/20",
  due_soon_tasks: "border-amber-200 bg-amber-50/40 dark:border-amber-500/20 dark:bg-amber-950/20",
  upcoming_tasks: "border-[#6B8F71]/20 bg-[#EDF2ED]/50 dark:border-[#8FB896]/20 dark:bg-[#8FB896]/5",
  in_progress_tasks: "border-[#C4856A]/20 bg-[#FDF3EE]/50 dark:border-[#D4A08A]/20 dark:bg-[#D4A08A]/5",
  completed_tasks: "border-stone-200 bg-stone-50/40 dark:border-stone-500/20 dark:bg-stone-950/20",
  cancelled_tasks: "border-slate-200 bg-slate-50/40 dark:border-slate-500/20 dark:bg-slate-950/20",
};

const COLUMN_HEADER_COLORS: Record<string, string> = {
  overdue_tasks: "text-red-700 dark:text-red-400",
  due_soon_tasks: "text-amber-700 dark:text-amber-400",
  upcoming_tasks: "text-[#6B8F71] dark:text-[#8FB896]",
  in_progress_tasks: "text-[#C4856A] dark:text-[#D4A08A]",
  completed_tasks: "text-stone-600 dark:text-stone-400",
  cancelled_tasks: "text-slate-600 dark:text-slate-400",
};

const COUNT_BADGE_COLORS: Record<string, string> = {
  overdue_tasks: "bg-red-100 text-red-700 dark:bg-red-900/50 dark:text-red-300",
  due_soon_tasks: "bg-amber-100 text-amber-700 dark:bg-amber-900/50 dark:text-amber-300",
  upcoming_tasks: "bg-[#6B8F71]/15 text-[#6B8F71] dark:bg-[#8FB896]/20 dark:text-[#8FB896]",
  in_progress_tasks: "bg-[#C4856A]/15 text-[#C4856A] dark:bg-[#D4A08A]/20 dark:text-[#D4A08A]",
  completed_tasks: "bg-stone-100 text-stone-700 dark:bg-stone-900/50 dark:text-stone-300",
  cancelled_tasks: "bg-slate-100 text-slate-700 dark:bg-slate-900/50 dark:text-slate-300",
};

interface KanbanColumnProps {
  column: KanbanColumnType;
}

function DraggableTask({ task }: { task: import("@/lib/api/tasks").TaskResponse }) {
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    isDragging,
  } = useDraggable({ id: task.id });

  const wasDragging = useRef(false);

  useEffect(() => {
    if (isDragging) {
      wasDragging.current = true;
    }
  }, [isDragging]);

  const style: React.CSSProperties = transform
    ? {
        transform: `translate(${transform.x}px, ${transform.y}px)`,
        opacity: isDragging ? 0.5 : 1,
        zIndex: isDragging ? 50 : undefined,
        position: isDragging ? "relative" : undefined,
      }
    : undefined as unknown as React.CSSProperties;

  // Block the click that fires after a drag ends so the Link doesn't navigate
  const handleClick = (e: React.MouseEvent) => {
    if (wasDragging.current) {
      e.preventDefault();
      e.stopPropagation();
      wasDragging.current = false;
    }
  };

  return (
    <div
      ref={setNodeRef}
      style={style}
      {...attributes}
      {...listeners}
      onClickCapture={handleClick}
    >
      <TaskCard task={task} isDragging={isDragging} />
    </div>
  );
}

export function KanbanColumn({ column }: KanbanColumnProps) {
  const { setNodeRef, isOver } = useDroppable({
    id: column.name,
  });

  return (
    <div
      className={cn(
        "flex flex-col min-w-[280px] sm:min-w-0 sm:flex-1 max-w-[320px] sm:max-w-none snap-center sm:snap-align-none rounded-2xl border p-3",
        COLUMN_COLORS[column.name] ?? "border-border bg-muted/30",
        isOver && "ring-2 ring-primary ring-offset-2"
      )}
    >
      <div className="flex items-center gap-2 mb-3 px-1">
        <h3
          className={cn(
            "font-heading font-semibold text-sm",
            COLUMN_HEADER_COLORS[column.name]
          )}
        >
          {column.display_name}
        </h3>
        <Badge
          variant="secondary"
          className={cn("text-xs rounded-md", COUNT_BADGE_COLORS[column.name])}
        >
          {column.count}
        </Badge>
      </div>

      <div ref={setNodeRef} className="flex-1 space-y-2 min-h-[60px]">
        {column.tasks.map((task) => (
          <DraggableTask key={task.id} task={task} />
        ))}
        {column.tasks.length === 0 && (
          <div className="flex items-center justify-center h-[60px] text-xs text-muted-foreground rounded-xl border border-dashed border-border/60">
            No tasks
          </div>
        )}
      </div>
    </div>
  );
}
