"use client";

import { useMemo, useState, useTransition } from "react";
import {
  DndContext,
  type DragEndEvent,
  DragOverlay,
  type DragStartEvent,
  PointerSensor,
  closestCorners,
  useDroppable,
  useSensor,
  useSensors,
} from "@dnd-kit/core";
import { SortableContext, verticalListSortingStrategy } from "@dnd-kit/sortable";
import { Loader2, Plus, Trash2 } from "lucide-react";
import { toast } from "sonner";

import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
  Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle,
} from "@/components/ui/dialog";
import { cn } from "@/lib/utils";
import { deleteLeadAction, moveLeadAction } from "@/lib/appwrite/lead-actions";

import { LeadCard } from "./lead-card";
import { LeadFormSheet } from "./lead-form-sheet";
import { LeadDetailSheet } from "./lead-detail-sheet";
import {
  COLUMNS,
  LEAD_STATUS_CONFIG,
  type ActivityRow,
  type LeadRow,
  type LeadStatus,
  type MemberOption,
} from "./types";
import { listLeadActivitiesForClient } from "./lead-activities-fetcher";

type Props = {
  leads: LeadRow[];
  members: MemberOption[];
  currentUserId: string;
};

function Column({
  status,
  leads,
  onAdd,
  onEdit,
  onDetail,
  onDelete,
}: {
  status: LeadStatus;
  leads: LeadRow[];
  onAdd: (status: LeadStatus) => void;
  onEdit: (lead: LeadRow) => void;
  onDetail: (lead: LeadRow) => void;
  onDelete: (lead: LeadRow) => void;
}) {
  const { setNodeRef, isOver } = useDroppable({
    id: `col-${status}`,
    data: { type: "column", status },
  });
  const cfg = LEAD_STATUS_CONFIG[status];
  const totalValue = leads.reduce((s, l) => s + (l.estimatedValue ?? 0), 0);

  return (
    <div className="bg-muted/40 flex min-w-[260px] flex-col rounded-lg border">
      <div className={cn("flex items-center justify-between border-b px-3 py-2.5", cfg.bg)}>
        <div className="flex items-center gap-2">
          <h2 className={cn("text-sm font-semibold", cfg.color)}>{LEAD_STATUS_CONFIG[status].label}</h2>
          <Badge variant="secondary" className="rounded-full px-1.5 py-0.5 text-xs">{leads.length}</Badge>
        </div>
        <Button variant="ghost" size="icon" className="size-7" onClick={() => onAdd(status)} aria-label="Yeni aday">
          <Plus className="size-3.5" />
        </Button>
      </div>
      {totalValue > 0 && (
        <div className="border-b px-3 py-1.5">
          <span className="text-muted-foreground text-xs">
            {new Intl.NumberFormat("tr-TR", { style: "currency", currency: "TRY", maximumFractionDigits: 0 }).format(totalValue)}
          </span>
        </div>
      )}
      <div
        ref={setNodeRef}
        className={cn("flex flex-1 flex-col gap-2 p-2 transition-colors", isOver && "bg-primary/5")}
      >
        <SortableContext items={leads.map((l) => l.id)} strategy={verticalListSortingStrategy}>
          {leads.map((lead) => (
            <LeadCard key={lead.id} lead={lead} onEdit={onEdit} onDetail={onDetail} onDelete={onDelete} />
          ))}
        </SortableContext>
        {leads.length === 0 && (
          <p className="text-muted-foreground py-8 text-center text-xs">Boş</p>
        )}
      </div>
    </div>
  );
}

export function LeadsBoard({ leads: initialLeads, members, currentUserId: _uid }: Props) {
  const [leads, setLeads] = useState<LeadRow[]>(initialLeads);
  const [activeId, setActiveId] = useState<string | null>(null);
  const [formOpen, setFormOpen] = useState(false);
  const [formStatus, setFormStatus] = useState<LeadStatus>("cold");
  const [editing, setEditing] = useState<LeadRow | null>(null);
  const [detailLead, setDetailLead] = useState<LeadRow | null>(null);
  const [detailActivities, setDetailActivities] = useState<ActivityRow[]>([]);
  const [detailOpen, setDetailOpen] = useState(false);
  const [deleting, setDeleting] = useState<LeadRow | null>(null);
  const [busy, startTransition] = useTransition();

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

  const grouped = useMemo(() => {
    const map = Object.fromEntries(COLUMNS.map((c) => [c.key, [] as LeadRow[]])) as Record<LeadStatus, LeadRow[]>;
    for (const l of leads) map[l.status].push(l);
    return map;
  }, [leads]);

  const activeLead = useMemo(() => leads.find((l) => l.id === activeId) ?? null, [leads, activeId]);

  const onDragStart = (e: DragStartEvent) => setActiveId(String(e.active.id));

  const onDragEnd = (e: DragEndEvent) => {
    const { active, over } = e;
    setActiveId(null);
    if (!over) return;

    const overData = over.data.current as { type?: string; status?: LeadStatus } | undefined;
    let targetStatus: LeadStatus | undefined;
    if (overData?.type === "column") targetStatus = overData.status;
    else if (overData?.type === "lead") targetStatus = overData.status;
    if (!targetStatus) return;

    const src = leads.find((l) => l.id === active.id);
    if (!src || src.status === targetStatus) return;

    setLeads((prev) => prev.map((l) => l.id === src.id ? { ...l, status: targetStatus! } : l));

    startTransition(async () => {
      const result = await moveLeadAction(src.id, targetStatus!);
      if (!result.ok) {
        setLeads((prev) => prev.map((l) => l.id === src.id ? { ...l, status: src.status } : l));
        toast.error(result.error ?? "Taşıma başarısız.");
      }
    });
  };

  const openDetail = async (lead: LeadRow) => {
    setDetailLead(lead);
    setDetailActivities([]);
    setDetailOpen(true);
    const acts = await listLeadActivitiesForClient(lead.id);
    setDetailActivities(acts);
  };

  const handleDelete = () => {
    if (!deleting) return;
    startTransition(async () => {
      const fd = new FormData();
      fd.set("id", deleting.id);
      const result = await deleteLeadAction(fd);
      if (result.ok) {
        toast.success("Aday silindi.");
        setLeads((prev) => prev.filter((l) => l.id !== deleting.id));
        setDeleting(null);
      } else {
        toast.error(result.error ?? "Silme başarısız.");
      }
    });
  };

  useMemo(() => setLeads(initialLeads), [initialLeads]);

  return (
    <>
      <div className="flex items-center justify-between">
        <div className="text-muted-foreground text-sm">
          Toplam {leads.length} aday
          {leads.filter((l) => l.status === "converted").length > 0 && (
            <span className="ml-2 text-green-600">
              · {leads.filter((l) => l.status === "converted").length} kazanıldı
            </span>
          )}
        </div>
        <Button onClick={() => { setEditing(null); setFormStatus("cold"); setFormOpen(true); }}>
          <Plus className="size-4" />
          Yeni aday
        </Button>
      </div>

      <DndContext sensors={sensors} collisionDetection={closestCorners} onDragStart={onDragStart} onDragEnd={onDragEnd}>
        <div className="flex gap-4 overflow-x-auto pb-4">
          {COLUMNS.map((col) => (
            <Column
              key={col.key}
              status={col.key}
              leads={grouped[col.key]}
              onAdd={(s) => { setEditing(null); setFormStatus(s); setFormOpen(true); }}
              onEdit={(l) => { setEditing(l); setFormOpen(true); }}
              onDetail={openDetail}
              onDelete={(l) => setDeleting(l)}
            />
          ))}
        </div>

        <DragOverlay>
          {activeLead && (
            <LeadCard lead={activeLead} onEdit={() => {}} onDetail={() => {}} onDelete={() => {}} isOverlay />
          )}
        </DragOverlay>
      </DndContext>

      <LeadFormSheet
        open={formOpen}
        onOpenChange={(v) => { setFormOpen(v); if (!v) setEditing(null); }}
        lead={editing}
        defaultStatus={formStatus}
        members={members}
        onCreated={(id) => {
          // Detail sheet will reload on next open; no-op here
        }}
      />

      <LeadDetailSheet
        open={detailOpen}
        onOpenChange={setDetailOpen}
        lead={detailLead}
        activities={detailActivities}
        onEdit={(l) => { setDetailOpen(false); setEditing(l); setFormOpen(true); }}
      />

      <Dialog open={Boolean(deleting)} onOpenChange={(v) => !v && setDeleting(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Adayı sil</DialogTitle>
            <DialogDescription>
              <strong>{deleting?.name}</strong> adlı aday ve tüm aktiviteleri kalıcı olarak silinecek.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="outline" onClick={() => setDeleting(null)} disabled={busy}>Vazgeç</Button>
            <Button variant="destructive" onClick={handleDelete} disabled={busy}>
              {busy ? <Loader2 className="size-4 animate-spin" /> : <Trash2 className="size-4" />}
              Sil
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
}
