import { format, isPast, isToday } from "date-fns";
import { motion, useReducedMotion } from "framer-motion";
import { useSortable } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import type { Card, Label } from "@/types/board";
import { LabelDots } from "@/components/board/LabelDots";
import { ChecklistBar } from "@/components/board/ChecklistBar";

interface CardThumbnailProps {
  card: Card;
  boardLabels: Label[];
  columnId: string;
  onCardClick?: (cardId: string) => void;
}

export function CardThumbnail({ card, boardLabels, columnId, onCardClick }: CardThumbnailProps) {
  const prefersReducedMotion = useReducedMotion();

  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging,
  } = useSortable({
    id: card.id,
    data: { type: "card", columnId },
  });

  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
    opacity: isDragging ? 0.3 : undefined,
  };

  const hasDueDate = card.dueDate != null;
  const dueDate = hasDueDate ? new Date(card.dueDate!) : null;
  const overdue = dueDate != null && isPast(dueDate) && !isToday(dueDate);

  function handleClick() {
    onCardClick?.(card.id);
  }

  return (
    <motion.button
      ref={setNodeRef}
      style={style}
      onClick={handleClick}
      className="w-full rounded-lg bg-pylon-surface p-3 shadow-sm text-left transition-all duration-200 hover:-translate-y-px hover:shadow-md"
      initial={prefersReducedMotion ? false : { opacity: 0, y: -8 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ type: "spring", stiffness: 300, damping: 25 }}
      {...attributes}
      {...listeners}
      role="article"
      aria-label={card.title}
    >
      {/* Label dots */}
      {card.labels.length > 0 && (
        <div className="mb-2">
          <LabelDots labelIds={card.labels} boardLabels={boardLabels} />
        </div>
      )}

      {/* Card title */}
      <p className="text-sm font-medium text-pylon-text">{card.title}</p>

      {/* Footer row: due date + checklist */}
      {(hasDueDate || card.checklist.length > 0) && (
        <div className="mt-2 flex items-center gap-3">
          {dueDate && (
            <span
              className={`font-mono text-xs ${
                overdue
                  ? "rounded bg-pylon-danger/10 px-1 py-0.5 text-pylon-danger"
                  : "text-pylon-text-secondary"
              }`}
            >
              {format(dueDate, "MMM d")}
            </span>
          )}
          {card.checklist.length > 0 && (
            <ChecklistBar checklist={card.checklist} />
          )}
        </div>
      )}
    </motion.button>
  );
}
