"use client";

import Link from "next/link";
import { useState, useTransition } from "react";

import { Spinner } from "@/components/common/Spinner";
import {
  KANBAN_STAGES,
  STAGE_COLORS,
  STAGE_LABELS,
  SOURCE_LABELS,
} from "@/lib/data/crm-constants";
import type { CrmStage, CrmCardSource } from "@prisma/client";

type Card = {
  id: string;
  title: string;
  contactName: string | null;
  contactEmail: string | null;
  contactPhone: string | null;
  stage: CrmStage;
  sourceType: CrmCardSource;
  dealValueRsd: number | null;
  winProbability: number;
  nextFollowUpAt: Date | null;
  tags: string[];
  _count: { notes: number };
  createdAt: Date;
};

interface PortalCrmKanbanProps {
  initialByStage: Record<CrmStage, Card[]>;
}

export function PortalCrmKanban({ initialByStage }: PortalCrmKanbanProps) {
  const [byStage, setByStage] = useState(initialByStage);
  const [draggedId, setDraggedId] = useState<string | null>(null);
  const [showNewModal, setShowNewModal] = useState(false);
  const [isPending, startTransition] = useTransition();

  function handleDrop(targetStage: CrmStage) {
    if (!draggedId) return;
    const card = findCardById(draggedId);
    if (!card || card.stage === targetStage) {
      setDraggedId(null);
      return;
    }

    // Optimistic UI update
    setByStage((prev) => {
      const next = { ...prev };
      next[card.stage] = next[card.stage].filter((c) => c.id !== draggedId);
      next[targetStage] = [{ ...card, stage: targetStage }, ...next[targetStage]];
      return next;
    });
    setDraggedId(null);

    startTransition(async () => {
      try {
        await fetch(`/api/portal/crm/${draggedId}`, {
          method: "PATCH",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ stage: targetStage }),
        });
      } catch (err) {
        console.error("[CRM] Stage update failed:", err);
        // Rollback ako padne
        setByStage(initialByStage);
      }
    });
  }

  function findCardById(id: string): Card | null {
    for (const stage of KANBAN_STAGES) {
      const found = byStage[stage].find((c) => c.id === id);
      if (found) return found;
    }
    return null;
  }

  return (
    <>
      <div className="mb-4 flex items-center justify-between gap-3">
        <p className="text-xs text-muted-foreground">
          {isPending ? "Sinhronizacija..." : "Prevuci kartice levo-desno za promenu stage-a"}
        </p>
        <button
          type="button"
          onClick={() => setShowNewModal(true)}
          className="rounded-lg bg-[#c2410c] px-4 py-2 text-xs font-bold text-white hover:bg-[#c8421f]"
        >
          + Novi lead
        </button>
      </div>

      <div className="grid grid-flow-col auto-cols-[280px] gap-3 overflow-x-auto pb-4">
        {KANBAN_STAGES.map((stage) => {
          const cards = byStage[stage];
          const color = STAGE_COLORS[stage];
          return (
            <div
              key={stage}
              onDragOver={(e) => e.preventDefault()}
              onDrop={() => handleDrop(stage)}
              className="rounded-2xl border border-border bg-[#faf9f7] p-3 min-h-[400px]"
            >
              <div className="flex items-center justify-between gap-2">
                <div className="flex items-center gap-2">
                  <span
                    className="inline-block h-2 w-2 rounded-full"
                    style={{ background: color }}
                  />
                  <h3 className="text-sm font-bold text-foreground">
                    {STAGE_LABELS[stage]}
                  </h3>
                  <span className="text-xs text-muted-foreground">
                    ({cards.length})
                  </span>
                </div>
              </div>
              <ul className="mt-3 space-y-2">
                {cards.length === 0 ? (
                  <li className="rounded-lg border border-dashed border-border bg-white/50 p-4 text-center text-[0.7rem] text-muted-foreground">
                    {stage === "NEW"
                      ? "Novi leadovi će se pojaviti ovde"
                      : "Prevuci karte ovde"}
                  </li>
                ) : (
                  cards.map((card) => (
                    <li
                      key={card.id}
                      draggable
                      onDragStart={() => setDraggedId(card.id)}
                      onDragEnd={() => setDraggedId(null)}
                      className="cursor-grab rounded-xl border border-border bg-white p-3 shadow-sm transition hover:border-[#c2410c]/40 active:cursor-grabbing"
                    >
                      <Link
                        href={`/portal/crm/${card.id}`}
                        className="block"
                      >
                        <div className="flex items-start justify-between gap-2">
                          <p className="line-clamp-2 text-sm font-semibold text-foreground">
                            {card.title}
                          </p>
                          <span
                            className="shrink-0 rounded-full px-1.5 py-0.5 text-[8px] font-bold uppercase tracking-wider"
                            style={{ background: color, color: "#fff" }}
                          >
                            {SOURCE_LABELS[card.sourceType].slice(0, 3)}
                          </span>
                        </div>
                        {card.contactName ? (
                          <p className="mt-1 truncate text-xs text-muted-foreground">
                            👤 {card.contactName}
                          </p>
                        ) : null}
                        {card.dealValueRsd ? (
                          <p className="mt-1.5 text-sm font-bold text-foreground">
                            💰 {card.dealValueRsd.toLocaleString("sr-RS")} RSD
                          </p>
                        ) : null}
                        <div className="mt-2 flex items-center justify-between text-[0.65rem] text-muted-foreground">
                          <span>{card.winProbability}% verovatnoća</span>
                          {card._count.notes > 0 ? (
                            <span>💬 {card._count.notes}</span>
                          ) : null}
                        </div>
                        {card.nextFollowUpAt ? (
                          <p className="mt-1 text-[0.65rem] font-semibold text-amber-700">
                            ⏰ Follow-up:{" "}
                            {new Intl.DateTimeFormat("sr-RS", {
                              day: "numeric",
                              month: "short",
                            }).format(card.nextFollowUpAt)}
                          </p>
                        ) : null}
                      </Link>
                    </li>
                  ))
                )}
              </ul>
            </div>
          );
        })}
      </div>

      {showNewModal ? <NewLeadModal onClose={() => setShowNewModal(false)} /> : null}
    </>
  );
}

function NewLeadModal({ onClose }: { onClose: () => void }) {
  const [isPending, startTransition] = useTransition();
  const [error, setError] = useState<string | null>(null);

  function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const form = e.currentTarget;
    const formData = new FormData(form);
    const body = {
      title: formData.get("title"),
      contactName: formData.get("contactName") || null,
      contactEmail: formData.get("contactEmail") || null,
      contactPhone: formData.get("contactPhone") || null,
      dealValueRsd: formData.get("dealValueRsd")
        ? Number(formData.get("dealValueRsd"))
        : null,
    };
    startTransition(async () => {
      try {
        const res = await fetch("/api/portal/crm", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(body),
        });
        if (!res.ok) {
          const data = await res.json().catch(() => ({}));
          throw new Error(data.error || "Greška");
        }
        onClose();
        window.location.reload();
      } catch (err) {
        setError(err instanceof Error ? err.message : "Greška pri unosu");
      }
    });
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
      <div className="w-full max-w-md rounded-3xl bg-white p-6 shadow-2xl">
        <h2 className="font-display text-xl font-bold text-foreground">Novi lead</h2>
        <p className="mt-1 text-xs text-muted-foreground">
          Ručno dodaj lead koji nije došao kroz platformu (npr. telefonski kontakt).
        </p>
        <form onSubmit={handleSubmit} className="mt-5 space-y-3">
          <Input name="title" label="Naslov *" required placeholder="Salon Cveta — web sajt" />
          <Input name="contactName" label="Ime kontakta" placeholder="Marija Marković" />
          <div className="grid gap-3 sm:grid-cols-2">
            <Input name="contactEmail" label="Email" type="email" />
            <Input name="contactPhone" label="Telefon" />
          </div>
          <Input name="dealValueRsd" label="Procena vrednosti (RSD)" type="number" />
          {error ? (
            <div className="rounded-lg border border-rose-300 bg-rose-50 p-2 text-xs text-rose-800">
              {error}
            </div>
          ) : null}
          <div className="flex items-center justify-end gap-2 pt-2">
            <button
              type="button"
              onClick={onClose}
              className="rounded-lg border border-border bg-[#faf9f7] px-4 py-2 text-xs font-semibold text-muted-foreground"
            >
              Otkaži
            </button>
            <button
              type="submit"
              disabled={isPending}
              className="inline-flex items-center justify-center gap-2 rounded-lg bg-[#c2410c] px-4 py-2 text-xs font-bold text-white disabled:opacity-60"
            >
              {isPending ? <Spinner className="h-4 w-4" /> : null}
              {isPending ? "Dodajem…" : "Dodaj lead"}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

function Input({ name, label, ...rest }: { name: string; label: string; [k: string]: unknown }) {
  return (
    <label className="block">
      <span className="text-xs font-semibold text-foreground">{label}</span>
      <input
        name={name}
        className="mt-1 w-full rounded-lg border border-border bg-[#faf9f7] px-3 py-2 text-sm focus:border-[#c2410c] focus:outline-none"
        {...(rest as React.InputHTMLAttributes<HTMLInputElement>)}
      />
    </label>
  );
}
