"use client";

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

type LeadStatus = "NEW" | "READ" | "REPLIED" | "ARCHIVED" | "SPAM";

type Lead = {
  id: string;
  name: string;
  email: string;
  phone: string | null;
  message: string;
  entityType: string;
  entityTitle: string;
  status: LeadStatus;
  createdAt: string;
  readAt: string | null;
  repliedAt: string | null;
  internalNotes: string | null;
};

type Props = {
  leads: Lead[];
  activeStatus: "ALL" | LeadStatus;
  counts: Record<LeadStatus | "TOTAL", number>;
};

const STATUS_LABELS: Record<LeadStatus, string> = {
  NEW: "Novo",
  READ: "Pročitano",
  REPLIED: "Odgovoreno",
  ARCHIVED: "Arhivirano",
  SPAM: "Spam",
};

const STATUS_COLOR: Record<LeadStatus, { bg: string; border: string; text: string }> = {
  NEW: { bg: "#fff4f0", border: "#fed7aa", text: "#c2410c" },
  READ: { bg: "#eff6ff", border: "#bfdbfe", text: "#1d4ed8" },
  REPLIED: { bg: "#ecfdf5", border: "#a7f3d0", text: "#047857" },
  ARCHIVED: { bg: "#faf9f7", border: "#ede8e3", text: "#6b7280" },
  SPAM: { bg: "#fef2f2", border: "#fecaca", text: "#b91c1c" },
};

const ENTITY_LABEL: Record<string, string> = {
  REAL_ESTATE: "Nekretnina",
  CAR: "Vozilo",
  EVENT: "Događaj",
  JOB: "Posao",
  COMPANY: "Profil",
  PRODUCT: "Proizvod",
};

function timeAgo(iso: string): string {
  const ts = new Date(iso).getTime();
  const diff = Date.now() - ts;
  const m = Math.floor(diff / 60000);
  if (m < 1) return "upravo sada";
  if (m < 60) return `pre ${m} min`;
  const h = Math.floor(m / 60);
  if (h < 24) return `pre ${h}h`;
  const d = Math.floor(h / 24);
  if (d < 30) return `pre ${d}d`;
  return new Date(iso).toLocaleDateString("sr-Latn-RS");
}

export function PortalLeadInbox({ leads, activeStatus, counts }: Props) {
  const router = useRouter();
  const [, startTransition] = useTransition();
  const [openId, setOpenId] = useState<string | null>(null);

  async function setStatus(leadId: string, status: LeadStatus) {
    try {
      const res = await fetch(`/api/portal/leads/${leadId}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ status }),
      });
      if (!res.ok) throw new Error("update failed");
      startTransition(() => router.refresh());
    } catch (err) {
      console.error(err);
      alert("Greška pri ažuriranju statusa.");
    }
  }

  return (
    <section className="partner-app-panel">
      {/* Filters */}
      <div className="flex flex-wrap items-center gap-2">
        {(["ALL", "NEW", "READ", "REPLIED", "ARCHIVED", "SPAM"] as const).map((s) => {
          const isActive = s === activeStatus;
          const count = s === "ALL" ? counts.TOTAL : counts[s];
          const label = s === "ALL" ? "Sve" : STATUS_LABELS[s];
          return (
            <Link
              key={s}
              href={s === "ALL" ? "/portal/upiti" : `/portal/upiti?status=${s.toLowerCase()}`}
              prefetch={false}
              className="inline-flex items-center gap-1.5 rounded-full border px-3.5 py-1.5 text-xs font-bold transition"
              style={{
                borderColor: isActive ? "#c2410c" : "#ede8e3",
                background: isActive ? "#fff4f0" : "white",
                color: isActive ? "#c2410c" : "#0c1828",
              }}
            >
              {label}
              <span
                className="rounded-full px-1.5 py-0.5 text-[0.6rem] font-bold text-white"
                style={{ background: isActive ? "#c2410c" : "#9ca3af" }}
              >
                {count}
              </span>
            </Link>
          );
        })}
      </div>

      {/* List */}
      {leads.length === 0 ? (
        <div className="mt-6 rounded-2xl border border-dashed border-[#ede8e3] bg-[#faf9f7] p-12 text-center">
          <p className="text-sm font-semibold text-[#0c1828]">Nema upita u ovoj kategoriji.</p>
          <p className="mt-1 text-xs text-[#6b7280]">
            Kada posetilac pošalje upit preko vašeg profila, pojaviće se ovde.
          </p>
        </div>
      ) : (
        <div className="mt-6 space-y-3">
          {leads.map((lead) => {
            const isOpen = openId === lead.id;
            const tone = STATUS_COLOR[lead.status];
            return (
              <article
                key={lead.id}
                className="overflow-hidden rounded-2xl border border-[#ede8e3] bg-white transition hover:shadow-[0_8px_24px_rgba(12,24,40,0.05)]"
              >
                <button
                  type="button"
                  onClick={() => {
                    setOpenId(isOpen ? null : lead.id);
                    if (!isOpen && lead.status === "NEW") {
                      void setStatus(lead.id, "READ");
                    }
                  }}
                  className="flex w-full items-start gap-4 p-5 text-left"
                >
                  <div className="flex-1 min-w-0">
                    <div className="flex flex-wrap items-center gap-2">
                      <span
                        className="inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[0.65rem] font-bold uppercase tracking-[0.12em]"
                        style={{
                          background: tone.bg,
                          border: `1px solid ${tone.border}`,
                          color: tone.text,
                        }}
                      >
                        {STATUS_LABELS[lead.status]}
                      </span>
                      <span className="text-[0.7rem] font-bold uppercase tracking-[0.12em] text-[#9ca3af]">
                        {ENTITY_LABEL[lead.entityType] || lead.entityType}
                      </span>
                      <span className="text-xs text-[#9ca3af]">· {timeAgo(lead.createdAt)}</span>
                    </div>

                    <p className="mt-2 truncate font-bold text-[#0c1828]">{lead.entityTitle}</p>
                    <p className="mt-1 text-sm text-[#6b7280]">
                      <span className="font-semibold text-[#0c1828]">{lead.name}</span> • {lead.email}
                      {lead.phone ? ` • ${lead.phone}` : ""}
                    </p>
                    {!isOpen && (
                      <p className="mt-2 line-clamp-2 text-sm leading-6 text-[#374151]">{lead.message}</p>
                    )}
                  </div>

                  <span className="text-[#9ca3af]">
                    <svg
                      width="14"
                      height="14"
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      strokeWidth="2.5"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      style={{
                        transform: isOpen ? "rotate(180deg)" : "rotate(0)",
                        transition: "transform 200ms",
                      }}
                    >
                      <polyline points="6 9 12 15 18 9" />
                    </svg>
                  </span>
                </button>

                {isOpen && (
                  <div className="border-t border-[#ede8e3] bg-[#faf9f7] p-5">
                    <p className="whitespace-pre-line text-[0.95rem] leading-7 text-[#374151]">
                      {lead.message}
                    </p>

                    <div className="mt-4 flex flex-wrap gap-2">
                      <a
                        href={`mailto:${lead.email}?subject=${encodeURIComponent(`Re: ${lead.entityTitle}`)}`}
                        className="inline-flex items-center gap-1.5 rounded-xl bg-[#c2410c] px-4 py-2.5 text-xs font-bold text-white transition hover:bg-[#d94e22]"
                        onClick={() => setStatus(lead.id, "REPLIED")}
                      >
                        <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
                          <path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z" />
                          <polyline points="22,6 12,13 2,6" />
                        </svg>
                        Odgovori e-mail
                      </a>
                      {lead.phone && (
                        <a
                          href={`tel:${lead.phone.replace(/\s+/g, "")}`}
                          className="inline-flex items-center gap-1.5 rounded-xl border border-[#ede8e3] bg-white px-3.5 py-2.5 text-xs font-bold text-[#0c1828] transition hover:border-[#c2410c]/30 hover:bg-[#fff4f0] hover:text-[#c2410c]"
                          onClick={() => setStatus(lead.id, "REPLIED")}
                        >
                          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
                            <path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07A19.5 19.5 0 0 1 4.69 13a19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 3.6 2.22h3a2 2 0 0 1 2 1.72c.127.96.361 1.903.7 2.81a2 2 0 0 1-.45 2.11L7.91 9.91a16 16 0 0 0 6.12 6.12l.95-.95a2 2 0 0 1 2.11-.45c.907.339 1.85.573 2.81.7A2 2 0 0 1 22 16.92z" />
                          </svg>
                          Pozovi {lead.phone}
                        </a>
                      )}
                      <button
                        type="button"
                        onClick={() => setStatus(lead.id, "REPLIED")}
                        className="inline-flex items-center gap-1.5 rounded-xl border border-[#ede8e3] bg-white px-3.5 py-2.5 text-xs font-bold text-[#0c1828] transition hover:border-emerald-300 hover:bg-emerald-50 hover:text-emerald-700"
                      >
                        ✓ Označi kao odgovoreno
                      </button>
                      <button
                        type="button"
                        onClick={() => setStatus(lead.id, "ARCHIVED")}
                        className="inline-flex items-center gap-1.5 rounded-xl border border-[#ede8e3] bg-white px-3.5 py-2.5 text-xs font-bold text-[#6b7280] transition hover:border-[#9ca3af] hover:bg-[#faf9f7]"
                      >
                        Arhiviraj
                      </button>
                      <button
                        type="button"
                        onClick={() => setStatus(lead.id, "SPAM")}
                        className="inline-flex items-center gap-1.5 rounded-xl border border-[#ede8e3] bg-white px-3.5 py-2.5 text-xs font-bold text-[#6b7280] transition hover:border-red-300 hover:bg-red-50 hover:text-red-700"
                      >
                        Spam
                      </button>
                    </div>
                  </div>
                )}
              </article>
            );
          })}
        </div>
      )}
    </section>
  );
}
