"use client";

import { useState } from "react";

import { useToast } from "@/components/admin/common/ToastProvider";
import { AdminTable, type AdminTableColumn } from "@/components/admin/tables/AdminTable";

const DISPUTE_STATUS_LABELS = {
  OPEN: "Otvoren",
  REVIEWED_OK: "Pregledano OK",
  WARNING_ISSUED: "Upozorenje izdato",
  RESOLVED: "Rešeno",
} as const;

type Dispute = {
  id: string;
  companyId: string;
  reason: string;
  status: keyof typeof DISPUTE_STATUS_LABELS;
  raisedByEmail: string | null;
  resolution: string | null;
  resolvedAt: string | null;
  createdAt: string;
  company: {
    id: string;
    name: string;
    slug: string;
    verificationLevel: number;
    isVerified: boolean;
  };
};

type SuspiciousCheck = {
  id: string;
  kind: string;
  status: string;
  rejectedReason: string | null;
  expiresAt: string | null;
  createdAt: string;
  updatedAt: string;
  company: {
    id: string;
    name: string;
    slug: string;
    verificationLevel: number;
    isVerified: boolean;
  };
};

type Props = {
  disputes: Dispute[];
  suspicious: SuspiciousCheck[];
};

const KIND_LABELS: Record<string, string> = {
  EMAIL: "Email",
  PHONE: "Telefon",
  APR: "APR",
  ADMIN_PREMIUM: "Admin premium",
};

const STATUS_LABELS: Record<string, string> = {
  PENDING: "Na čekanju",
  APPROVED: "Odobreno",
  REJECTED: "Odbijeno",
  EXPIRED: "Isteklo",
};

function fmtDate(iso: string | null) {
  if (!iso) return "—";
  return new Date(iso).toLocaleString("sr-RS", {
    day: "2-digit",
    month: "2-digit",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  });
}

export function TrustSafetyManager({ disputes, suspicious }: Props) {
  const [tab, setTab] = useState<"disputes" | "suspicious">("disputes");
  const [working, setWorking] = useState<string | null>(null);
  const [filter, setFilter] = useState<string>("OPEN");
  const toast = useToast();

  async function handleResolve(
    dispute: Dispute,
    status: "REVIEWED_OK" | "WARNING_ISSUED" | "RESOLVED",
  ) {
    const resolution = window.prompt(
      `Komentar uz status "${DISPUTE_STATUS_LABELS[status]}" (opciono):`,
      "",
    );
    if (resolution === null) return;

    setWorking(dispute.id);
    try {
      const res = await fetch("/api/admin/trust-safety/dispute", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ disputeId: dispute.id, status, resolution }),
      });
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      toast.success("Prijava je ažurirana.");
      window.location.reload();
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Greška pri rešavanju.");
      setWorking(null);
    }
  }

  const filteredDisputes = filter === "ALL" ? disputes : disputes.filter((d) => d.status === filter);
  const counts = disputes.reduce<Record<string, number>>((acc, d) => {
    acc[d.status] = (acc[d.status] ?? 0) + 1;
    return acc;
  }, {});

  return (
    <div className="space-y-6">
      {/* Errors surface via toast notifications. */}
      {/* Tabs */}
      <div className="flex gap-2 border-b border-[#ede8e3]">
        <button
          type="button"
          onClick={() => setTab("disputes")}
          className={`px-4 py-2 text-sm font-semibold transition ${
            tab === "disputes"
              ? "border-b-2 border-orange-500 text-[#0c1828]"
              : "text-[#6b7280] hover:text-[#0c1828]"
          }`}
        >
          Sporovi · {disputes.length}
        </button>
        <button
          type="button"
          onClick={() => setTab("suspicious")}
          className={`px-4 py-2 text-sm font-semibold transition ${
            tab === "suspicious"
              ? "border-b-2 border-orange-500 text-[#0c1828]"
              : "text-[#6b7280] hover:text-[#0c1828]"
          }`}
        >
          Sumnjive verifikacije · {suspicious.length}
        </button>
      </div>

      {tab === "disputes" && (
        <>
          <div className="flex flex-wrap gap-2">
            {(["OPEN", "REVIEWED_OK", "WARNING_ISSUED", "RESOLVED", "ALL"] as const).map((f) => (
              <button
                key={f}
                type="button"
                onClick={() => setFilter(f)}
                className={`rounded-full px-3 py-1.5 text-xs font-semibold ${
                  filter === f
                    ? "bg-[#c2410c] text-white"
                    : "border border-[#ede8e3] text-[#374151] hover:border-[#c2410c]/40"
                }`}
              >
                {f === "ALL" ? "Svi" : DISPUTE_STATUS_LABELS[f]}
                {f !== "ALL" && counts[f] ? ` · ${counts[f]}` : ""}
              </button>
            ))}
          </div>

          {filteredDisputes.length === 0 ? (
            <p className="text-sm text-[#6b7280]">Nema sporova u ovom statusu.</p>
          ) : (
            <div className="space-y-3">
              {filteredDisputes.map((d) => (
                <div
                  key={d.id}
                  className="rounded-2xl border border-[#ede8e3] bg-white p-5"
                >
                  <div className="flex flex-wrap items-start justify-between gap-3">
                    <div>
                      <a
                        href={`/admin/kompanije?focus=${d.companyId}`}
                        className="text-base font-semibold text-[#0c1828] hover:text-[#c2410c]"
                      >
                        {d.company.name}
                      </a>
                      <div className="mt-0.5 text-xs text-[#6b7280]">
                        Nivo verifikacije: {d.company.verificationLevel} ·{" "}
                        {d.company.isVerified ? "Verifikovano" : "Nije verifikovano"} ·{" "}
                        Prijavljeno: {fmtDate(d.createdAt)}
                      </div>
                    </div>
                    <span
                      className={`rounded-full px-2 py-0.5 text-xs font-semibold ${
                        d.status === "OPEN"
                          ? "bg-amber-50 text-amber-700 ring-1 ring-amber-200"
                          : d.status === "WARNING_ISSUED"
                            ? "bg-rose-50 text-rose-700 ring-1 ring-rose-200"
                            : "bg-emerald-50 text-emerald-700 ring-1 ring-emerald-200"
                      }`}
                    >
                      {DISPUTE_STATUS_LABELS[d.status]}
                    </span>
                  </div>

                  <p className="mt-3 whitespace-pre-wrap rounded-lg border border-[#ede8e3] bg-[#faf9f7] p-3 text-sm leading-relaxed text-[#374151]">
                    {d.reason}
                  </p>

                  {d.raisedByEmail && (
                    <p className="mt-2 text-xs text-[#6b7280]">
                      Prijavio: <span className="font-mono">{d.raisedByEmail}</span>
                    </p>
                  )}

                  {d.resolution && (
                    <p className="mt-2 text-xs text-[#6b7280]">
                      <span className="font-semibold text-[#374151]">Komentar:</span>{" "}
                      {d.resolution}
                    </p>
                  )}

                  {d.status === "OPEN" && (
                    <div className="mt-4 flex flex-wrap gap-2">
                      <button
                        type="button"
                        disabled={working === d.id}
                        onClick={() => handleResolve(d, "REVIEWED_OK")}
                        className="rounded-lg border border-emerald-500/40 bg-emerald-500/10 px-3 py-1.5 text-xs font-semibold text-emerald-200 hover:bg-emerald-500/20 disabled:opacity-50"
                      >
                        Pregledano OK
                      </button>
                      <button
                        type="button"
                        disabled={working === d.id}
                        onClick={() => handleResolve(d, "WARNING_ISSUED")}
                        className="rounded-lg border border-rose-500/40 bg-rose-500/10 px-3 py-1.5 text-xs font-semibold text-rose-200 hover:bg-rose-500/20 disabled:opacity-50"
                      >
                        Izdaj upozorenje (skida verifikaciju)
                      </button>
                      <button
                        type="button"
                        disabled={working === d.id}
                        onClick={() => handleResolve(d, "RESOLVED")}
                        className="rounded-lg border border-[#ede8e3] px-3 py-1.5 text-xs font-semibold text-[#374151] hover:bg-[#0c1828]/5 disabled:opacity-50"
                      >
                        Rešeno
                      </button>
                    </div>
                  )}
                </div>
              ))}
            </div>
          )}
        </>
      )}

      {tab === "suspicious" && (
        <>
          {suspicious.length === 0 ? (
            <p className="text-sm text-[#6b7280]">Nema sumnjivih verifikacija.</p>
          ) : (
            <div className="overflow-x-auto">
              <AdminTable<SuspiciousCheck>
                getRowKey={(row) => row.id}
                richColumns={
                  [
                    {
                      key: "company",
                      label: "Firma",
                      render: (row) => (
                        <>
                          <a
                            href={`/admin/kompanije?focus=${row.company.id}`}
                            className="text-[#374151] hover:text-[#c2410c]"
                          >
                            {row.company.name}
                          </a>
                          <div className="text-xs text-[#6b7280]">
                            Nivo {row.company.verificationLevel}
                          </div>
                        </>
                      ),
                    },
                    {
                      key: "kind",
                      label: "Tip",
                      cellClassName: "text-[#374151]",
                      render: (row) => KIND_LABELS[row.kind] ?? row.kind,
                    },
                    {
                      key: "status",
                      label: "Status",
                      render: (row) => (
                        <span
                          className={`rounded-full px-2 py-0.5 text-xs ${
                            row.status === "PENDING"
                              ? "bg-amber-50 text-amber-700 ring-1 ring-amber-200"
                              : row.status === "REJECTED"
                                ? "bg-rose-50 text-rose-700 ring-1 ring-rose-200"
                                : "bg-[#0c1828]/8 text-[#374151]"
                          }`}
                        >
                          {STATUS_LABELS[row.status] ?? row.status}
                        </span>
                      ),
                    },
                    {
                      key: "reason",
                      label: "Razlog/Ističe",
                      cellClassName: "text-[#6b7280]",
                      render: (row) =>
                        row.rejectedReason ||
                        (row.expiresAt && new Date(row.expiresAt) < new Date()
                          ? `Isteklo: ${fmtDate(row.expiresAt)}`
                          : "Čeka ručnu obradu"),
                    },
                    {
                      key: "updatedAt",
                      label: "Ažurirano",
                      cellClassName: "text-[#6b7280]",
                      render: (row) => fmtDate(row.updatedAt),
                    },
                  ] satisfies AdminTableColumn<SuspiciousCheck>[]
                }
                richRows={suspicious}
              />
            </div>
          )}
        </>
      )}
    </div>
  );
}
