'use client';

import { useSortable } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { differenceInDays } from 'date-fns';

import { Badge } from '@/components/ui/badge';
import { deriveInterestBerthLabel } from '@/lib/templates/interest-berth-label';

interface PipelineCardProps {
  id: string;
  clientName: string | null;
  berthMooringNumber: string | null;
  /** Every linked berth's mooring (sorted) - drives the multi-berth label.
   *  Falls back to `berthMooringNumber` alone when empty / absent. */
  berthMoorings?: string[];
  leadCategory: string | null;
  updatedAt: string | Date;
}

const LEAD_CATEGORY_COLORS: Record<string, string> = {
  general_interest: 'secondary',
  specific_qualified: 'default',
  hot_lead: 'destructive',
};

export function PipelineCard({
  id,
  clientName,
  berthMooringNumber,
  berthMoorings,
  leadCategory,
  updatedAt,
}: PipelineCardProps) {
  const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
    id,
  });

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

  const daysInStage = differenceInDays(new Date(), new Date(updatedAt));
  const berthLabel = deriveInterestBerthLabel(berthMoorings) ?? berthMooringNumber;

  return (
    <div
      ref={setNodeRef}
      style={style}
      {...attributes}
      {...listeners}
      className="bg-card border rounded-md p-3 shadow-sm cursor-grab active:cursor-grabbing space-y-2"
    >
      <p className="text-sm font-medium truncate">{clientName ?? 'Unknown client'}</p>

      {berthLabel && <p className="text-xs text-muted-foreground">Berth: {berthLabel}</p>}

      <div className="flex items-center justify-between gap-2">
        {leadCategory && (
          <Badge
            variant={
              (LEAD_CATEGORY_COLORS[leadCategory] as
                | 'default'
                | 'secondary'
                | 'destructive'
                | 'outline') ?? 'secondary'
            }
          >
            {leadCategory.replace(/_/g, ' ')}
          </Badge>
        )}
        <span className="text-xs text-muted-foreground ml-auto">{daysInStage}d</span>
      </div>
    </div>
  );
}
