"use client";

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

import { Spinner } from "@/components/common/Spinner";

type Status = "PENDING" | "PUBLISHED" | "PRIVATE" | "REJECTED";

type Item = {
  id: string;
  question: string;
  answer: string | null;
  status: Status;
  questionerName: string;
  questionerEmail: string;
  createdAt: string;
  answeredAt: string | null;
  publishedAt: string | null;
};

type Props = {
  items: Item[];
  activeStatus: "ALL" | Status;
  counts: Record<Status | "TOTAL", number>;
};

const STATUS_LABELS: Record<Status, string> = {
  PENDING: "Na čekanju",
  PUBLISHED: "Javno",
  PRIVATE: "Privatno",
  REJECTED: "Odbijeno",
};

const STATUS_COLOR: Record<Status, { bg: string; border: string; text: string }> = {
  PENDING: { bg: "#fff4f0", border: "#fed7aa", text: "#c2410c" },
  PUBLISHED: { bg: "#ecfdf5", border: "#a7f3d0", text: "#047857" },
  PRIVATE: { bg: "#eff6ff", border: "#bfdbfe", text: "#1d4ed8" },
  REJECTED: { bg: "#faf9f7", border: "#ede8e3", text: "#6b7280" },
};

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 PortalQuestionsModeration({ items, activeStatus, counts }: Props) {
  const router = useRouter();
  const [, startTransition] = useTransition();
  const [drafts, setDrafts] = useState<Record<string, string>>({});
  const [busyId, setBusyId] = useState<string | null>(null);
  const [aiBusyId, setAiBusyId] = useState<string | null>(null);
  const [aiNote, setAiNote] = useState<Record<string, string>>({});

  async function suggestAi(id: string, question: string) {
    setAiBusyId(id);
    setAiNote({ ...aiNote, [id]: "" });
    try {
      const res = await fetch("/api/portal/questions/suggest", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ question }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data?.error || "AI ne radi.");
      setDrafts({ ...drafts, [id]: data.suggestion.answer });
      const conf = Math.round((data.suggestion.confidence ?? 0) * 100);
      setAiNote({
        ...aiNote,
        [id]: `AI predlog (sigurnost ${conf}%) — proveri pre slanja.`,
      });
    } catch (err) {
      setAiNote({
        ...aiNote,
        [id]: err instanceof Error ? err.message : "AI nije uspeo.",
      });
    } finally {
      setAiBusyId(null);
    }
  }

  async function submit(id: string, visibility: "PUBLISHED" | "PRIVATE") {
    const answer = (drafts[id] ?? "").trim();
    if (!answer) {
      alert("Odgovor ne može biti prazan.");
      return;
    }
    setBusyId(id);
    try {
      const res = await fetch(`/api/portal/questions/${id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ action: "answer", answer, visibility }),
      });
      if (!res.ok) throw new Error("update failed");
      startTransition(() => router.refresh());
    } catch (err) {
      console.error(err);
      alert("Greška pri slanju odgovora.");
    } finally {
      setBusyId(null);
    }
  }

  async function reject(id: string) {
    if (!window.confirm("Sigurno odbiti pitanje? Postavljač neće dobiti odgovor.")) return;
    setBusyId(id);
    try {
      const res = await fetch(`/api/portal/questions/${id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ action: "reject" }),
      });
      if (!res.ok) throw new Error("update failed");
      startTransition(() => router.refresh());
    } catch (err) {
      console.error(err);
      alert("Greška pri odbacivanju.");
    } finally {
      setBusyId(null);
    }
  }

  const inputCls =
    "w-full rounded-xl border border-[#ede8e3] bg-white px-3.5 py-2.5 text-sm text-[#0c1828] placeholder:text-[#9ca3af] outline-none transition focus:border-[#c2410c]/40 focus:ring-2 focus:ring-[#c2410c]/15";

  return (
    <section className="partner-app-panel">
      <div className="flex flex-wrap items-center gap-2">
        {(["ALL", "PENDING", "PUBLISHED", "PRIVATE", "REJECTED"] 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/pitanja" : `/portal/pitanja?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>

      {items.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 pitanja u ovoj kategoriji.</p>
          <p className="mt-1 text-xs text-[#6b7280]">
            Posetioci mogu da postave pitanje na vašem javnom profilu — pojaviće se ovde.
          </p>
        </div>
      ) : (
        <div className="mt-6 space-y-3">
          {items.map((q) => {
            const tone = STATUS_COLOR[q.status];
            const isPending = q.status === "PENDING";
            return (
              <article
                key={q.id}
                className="overflow-hidden rounded-2xl border border-[#ede8e3] bg-white"
              >
                <div className="p-5">
                  <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[q.status]}
                    </span>
                    <span className="text-xs text-[#9ca3af]">{timeAgo(q.createdAt)}</span>
                  </div>

                  <p className="mt-3 text-[0.95rem] font-semibold leading-snug text-[#0c1828]">
                    {q.question}
                  </p>
                  <p className="mt-2 text-xs text-[#6b7280]">
                    Postavio/la: <strong className="text-[#0c1828]">{q.questionerName}</strong> ·{" "}
                    {q.questionerEmail}
                  </p>

                  {q.answer ? (
                    <div className="mt-4 rounded-xl border border-emerald-100 bg-emerald-50/50 p-4">
                      <p className="text-xs font-bold uppercase tracking-[0.12em] text-emerald-700">
                        Vaš odgovor {q.publishedAt ? "(javno)" : "(privatno)"}
                      </p>
                      <p className="mt-2 whitespace-pre-line text-sm leading-7 text-[#374151]">
                        {q.answer}
                      </p>
                    </div>
                  ) : isPending ? (
                    <div className="mt-4 space-y-3">
                      <textarea
                        rows={4}
                        placeholder="Napišite odgovor (ide na e-mail posetioca)..."
                        value={drafts[q.id] ?? ""}
                        onChange={(e) => setDrafts({ ...drafts, [q.id]: e.target.value })}
                        className={`${inputCls} resize-none`}
                      />
                      {aiNote[q.id] && (
                        <p className="rounded-lg border border-orange-200 bg-orange-50 px-3 py-2 text-[0.75rem] font-semibold text-orange-700">
                          ✨ {aiNote[q.id]}
                        </p>
                      )}
                      <div className="flex flex-wrap gap-2">
                        <button
                          type="button"
                          disabled={aiBusyId === q.id}
                          onClick={() => suggestAi(q.id, q.question)}
                          className="inline-flex items-center gap-1.5 rounded-xl border border-orange-300 bg-orange-50 px-4 py-2.5 text-xs font-bold text-orange-700 transition hover:bg-orange-100 disabled:opacity-60"
                        >
                          {aiBusyId === q.id ? <Spinner className="h-4 w-4" /> : null}
                          {aiBusyId === q.id ? "AI generiše..." : "✨ Predloži AI odgovor"}
                        </button>
                        <button
                          type="button"
                          disabled={busyId === q.id}
                          onClick={() => submit(q.id, "PUBLISHED")}
                          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] disabled:opacity-60"
                        >
                          {busyId === q.id ? <Spinner className="h-4 w-4" /> : null}
                          ✓ Odgovori i objavi javno
                        </button>
                        <button
                          type="button"
                          disabled={busyId === q.id}
                          onClick={() => submit(q.id, "PRIVATE")}
                          className="inline-flex items-center gap-1.5 rounded-xl border border-[#ede8e3] bg-white px-4 py-2.5 text-xs font-bold text-[#0c1828] transition hover:border-[#c2410c]/30 hover:bg-[#fff4f0] hover:text-[#c2410c] disabled:opacity-60"
                        >
                          {busyId === q.id ? <Spinner className="h-4 w-4" /> : null}
                          Odgovori privatno (samo e-mail)
                        </button>
                        <button
                          type="button"
                          disabled={busyId === q.id}
                          onClick={() => reject(q.id)}
                          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 disabled:opacity-60"
                        >
                          Odbaci
                        </button>
                      </div>
                    </div>
                  ) : null}
                </div>
              </article>
            );
          })}
        </div>
      )}
    </section>
  );
}
