"use client";

import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import {
  DndContext,
  DragEndEvent,
  DragOverlay,
  PointerSensor,
  KeyboardSensor,
  useSensor,
  useSensors,
  useDroppable,
  useDraggable,
} from "@dnd-kit/core";
import { updateLeadField } from "@/app/admin/pipeline/actions";
import type { LeadWithTags } from "@/lib/admin-queries";
import { StatusBadge } from "@/components/ui/StatusBadge";

type LeadStage = "contacted" | "qualified" | "proposal_sent" | "negotiating" | "won" | "lost";

const LEAD_COLUMNS: {
  id: LeadStage;
  label: string;
}[] = [
  { id: "contacted",     label: "Contattato" },
  { id: "qualified",     label: "Qualificato" },
  { id: "proposal_sent", label: "Offerta inviata" },
  { id: "negotiating",   label: "Trattativa" },
  { id: "won",           label: "Vinto" },
  { id: "lost",          label: "Perso" },
];

const VALID_STAGES = LEAD_COLUMNS.map((c) => c.id) as string[];

function DroppableColumn({
  id, label, leads, activeId,
}: {
  id: LeadStage;
  label: string;
  leads: LeadWithTags[];
  activeId: string | null;
}) {
  const { setNodeRef, isOver } = useDroppable({ id });

  return (
    <div
      ref={setNodeRef}
      className={`w-[280px] shrink-0 flex flex-col gap-4 rounded-xl border p-4 transition-colors min-h-[420px] ${
        isOver ? "border-primary bg-primary/5" : "border-border-light bg-muted/60"
      }`}
    >
      <div className="flex items-center justify-between border-b border-border-light pb-2">
        <span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">{label}</span>
        <span className="text-xs font-medium tabular-nums bg-secondary text-muted-foreground px-2 py-0.5 rounded-full">
          {leads.length}
        </span>
      </div>

      <div className="flex-1 flex flex-col gap-2">
        {leads.map((lead) => (
          <DraggableLeadCard key={lead.id} lead={lead} status={id} isActive={activeId === lead.id} />
        ))}
        {leads.length === 0 && (
          <p className="text-xs text-muted-foreground italic text-center py-10 select-none">
            Nessun lead
          </p>
        )}
      </div>
    </div>
  );
}

function DraggableLeadCard({
  lead,
  status,
  isActive,
}: {
  lead: LeadWithTags;
  status: LeadStage;
  isActive: boolean;
}) {
  const { attributes, listeners, setNodeRef, transform, isDragging } = useDraggable({ id: lead.id });

  const style = transform
    ? { transform: `translate3d(${transform.x}px, ${transform.y}px, 0)` }
    : undefined;

  return (
    <div
      ref={setNodeRef}
      style={style}
      {...listeners}
      {...attributes}
      className={`bg-card p-4 rounded-lg border border-border shadow-sm cursor-grab active:cursor-grabbing select-none transition-all duration-200 ${
        isDragging ? "opacity-30" : "hover:border-primary/30 hover:shadow-card-hover"
      }`}
    >
      <div className="flex justify-between items-start gap-2 mb-2">
        <p className="text-xs font-semibold text-foreground">{lead.name}</p>
        <StatusBadge status={status} className="rounded px-1.5 py-0.5 text-[9px]" />
      </div>
      {lead.email && (
        <p className="text-[11px] text-muted-foreground mb-3 line-clamp-1">{lead.email}</p>
      )}
      <div className="flex justify-between items-center text-[10px] text-muted-foreground">
        <span className="font-medium">{lead.company ?? ""}</span>
        <span>Tag +</span>
      </div>
    </div>
  );
}

export function LeadsKanbanBoard({ leads }: { leads: LeadWithTags[] }) {
  const router = useRouter();
  const [, startTransition] = useTransition();
  const [activeId, setActiveId] = useState<string | null>(null);

  const [leadStatuses, setLeadStatuses] = useState<Record<string, LeadStage>>(() =>
    Object.fromEntries(leads.map((l) => [l.id, l.status as LeadStage]))
  );

  const sensors = useSensors(
    useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),
    useSensor(KeyboardSensor)
  );

  const leadsByStage = LEAD_COLUMNS.reduce(
    (acc, col) => {
      acc[col.id] = leads.filter((l) => (leadStatuses[l.id] ?? l.status) === col.id);
      return acc;
    },
    {} as Record<LeadStage, LeadWithTags[]>
  );

  const activeLead = activeId ? leads.find((l) => l.id === activeId) : null;

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

    const leadId = active.id as string;
    const newStage = over.id as LeadStage;
    const currentStage = leadStatuses[leadId];

    if (!VALID_STAGES.includes(newStage)) return;
    if (newStage === currentStage) return;

    setLeadStatuses((prev) => ({ ...prev, [leadId]: newStage }));

    startTransition(async () => {
      await updateLeadField(leadId, "status", newStage);
      router.refresh();
    });
  }

  return (
    <DndContext
      sensors={sensors}
      onDragStart={(e) => setActiveId(e.active.id as string)}
      onDragEnd={handleDragEnd}
    >
      <div className="overflow-x-auto">
        <div className="flex gap-4">
          {LEAD_COLUMNS.map((col) => (
            <DroppableColumn
              key={col.id}
              {...col}
              leads={leadsByStage[col.id]}
              activeId={activeId}
            />
          ))}
        </div>
      </div>

      <DragOverlay dropAnimation={null}>
        {activeLead && (
          <div className="bg-card rounded-lg border-2 border-primary p-4 shadow-xl rotate-1 pointer-events-none">
            <p className="text-xs font-semibold text-foreground mb-2">{activeLead.name}</p>
            {activeLead.company && (
              <p className="text-[10px] text-muted-foreground font-medium">{activeLead.company}</p>
            )}
          </div>
        )}
      </DragOverlay>
    </DndContext>
  );
}
