"use client";

import { useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
  Loader2,
  Wallet,
  Search,
  ChevronLeft,
  ChevronRight,
  CheckCircle2,
  XCircle,
  AlertTriangle,
  Copy,
  Clock,
} from "lucide-react";
import { toast } from "sonner";
import { adminApi } from "@/lib/api/client";
import { cn } from "@/lib/utils/cn";

/* ───────────────────────────── Types ───────────────────────────── */

type PaymentStatus =
  | "PENDING"
  | "AWAITING_CONFIRMATION"
  | "SUCCESS"
  | "REJECTED"
  | "CANCELLED"
  | "FAILED"
  | "REFUNDED";

interface PaymentRow {
  id: string;
  status: PaymentStatus;
  method: string;
  paperId: string | null;
  paperReferenceNo: string | null;
  paperTitleHi: string | null;
  paperTitleEn: string | null;
  authorNameHi: string | null;
  authorNameEn: string | null;
  authorEmail: string | null;
  authorPhone: string | null;
  amountPaise: number;
  gstPaise: number;
  totalPaise: number;
  reference: string | null;
  payerNote: string | null;
  declaredAt: string | null;
  confirmedAt: string | null;
  confirmedByName: string | null;
  rejectionReason: string | null;
  duplicateReference: boolean;
  stale: boolean;
}

interface Summary {
  awaitingCount: number;
  staleCount: number;
  confirmedThisMonthCount: number;
  confirmedThisMonthPaise: number;
  confirmedThisYearCount: number;
  confirmedThisYearPaise: number;
  staleAfterDays: number;
}

interface PageResponse<T> {
  content: T[];
  totalElements: number;
  totalPages: number;
  number: number;
}

/* ───────────────────────────── Helpers ───────────────────────────── */

const inr = (paise: number) =>
  `₹${(paise / 100).toLocaleString("en-IN", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;

const when = (iso: string | null) =>
  iso
    ? new Date(iso).toLocaleString("en-IN", { dateStyle: "medium", timeStyle: "short" })
    : "—";

const FILTERS: { value: PaymentStatus | ""; hi: string; en: string }[] = [
  { value: "AWAITING_CONFIRMATION", hi: "सत्यापन हेतु", en: "To verify" },
  { value: "", hi: "सभी", en: "All" },
  { value: "PENDING", hi: "भुगतान शेष", en: "Not paid yet" },
  { value: "SUCCESS", hi: "पुष्ट", en: "Confirmed" },
  { value: "REJECTED", hi: "अस्वीकृत", en: "Rejected" },
  { value: "CANCELLED", hi: "रद्द", en: "Cancelled" },
];

const STATUS_STYLE: Record<PaymentStatus, { cls: string; hi: string; en: string }> = {
  PENDING: { cls: "bg-gray-100 text-gray-700", hi: "भुगतान शेष", en: "Not paid yet" },
  AWAITING_CONFIRMATION: { cls: "bg-amber-100 text-amber-800", hi: "सत्यापन हेतु", en: "To verify" },
  SUCCESS: { cls: "bg-green-100 text-green-800", hi: "पुष्ट", en: "Confirmed" },
  REJECTED: { cls: "bg-red-100 text-red-700", hi: "अस्वीकृत", en: "Rejected" },
  // Not a failure and nobody's fault: the fee stopped existing when the editor
  // switched the payment section off, so it is greyed out rather than flagged.
  CANCELLED: { cls: "bg-gray-100 text-gray-500", hi: "रद्द", en: "Cancelled" },
  FAILED: { cls: "bg-red-100 text-red-700", hi: "विफल", en: "Failed" },
  REFUNDED: { cls: "bg-blue-100 text-blue-700", hi: "वापस", en: "Refunded" },
};

/* ───────────────────────────── Page ───────────────────────────── */

export default function AdminPaymentsPage() {
  // Opens on the queue that needs attention, not on everything.
  const [status, setStatus] = useState<PaymentStatus | "">("AWAITING_CONFIRMATION");
  const [searchInput, setSearchInput] = useState("");
  const [search, setSearch] = useState("");
  const [page, setPage] = useState(0);
  const [rejecting, setRejecting] = useState<PaymentRow | null>(null);
  const [reason, setReason] = useState("");

  const qc = useQueryClient();

  const summaryQuery = useQuery({
    queryKey: ["admin", "payments", "summary"],
    queryFn: async () => (await adminApi.paymentSummary()).data as Summary,
  });

  const listQuery = useQuery({
    queryKey: ["admin", "payments", status, search, page],
    queryFn: async () =>
      (
        await adminApi.payments({
          status: status || undefined,
          search: search || undefined,
          page,
          size: 20,
          sort: "declaredAt,asc",
        })
      ).data as PageResponse<PaymentRow>,
  });

  const refresh = () => {
    qc.invalidateQueries({ queryKey: ["admin", "payments"] });
  };

  const confirmMutation = useMutation({
    mutationFn: (id: string) => adminApi.confirmPayment(id),
    onSuccess: () => {
      toast.success("भुगतान पुष्ट — शोधपत्र समीक्षा में भेजा गया / Payment confirmed — paper released to review");
      refresh();
    },
    onError: (err: unknown) =>
      toast.error(
        (err as { response?: { data?: { message?: string } } })?.response?.data?.message ??
          "Could not confirm the payment"
      ),
  });

  const rejectMutation = useMutation({
    mutationFn: ({ id, reason }: { id: string; reason: string }) =>
      adminApi.rejectPayment(id, reason),
    onSuccess: () => {
      toast.success("अस्वीकृत — लेखक को सूचित कर दिया गया / Rejected — the author has been told");
      setRejecting(null);
      setReason("");
      refresh();
    },
    onError: (err: unknown) =>
      toast.error(
        (err as { response?: { data?: { message?: string } } })?.response?.data?.message ??
          "Could not reject the payment"
      ),
  });

  const summary = summaryQuery.data;
  const rows = listQuery.data?.content ?? [];

  return (
    <div className="p-6 max-w-7xl mx-auto">
      <div className="flex items-center gap-2 mb-1">
        <Wallet className="h-6 w-6 text-indigo-600" />
        <h1 className="text-2xl font-bold text-gray-900">भुगतान / Payments</h1>
      </div>
      <p className="text-sm text-gray-500 mb-6">
        समीक्षा शुल्क का मिलान बैंक विवरण से करें। पुष्टि के बाद ही शोधपत्र समीक्षा में जाता है।
        <br />
        Match review fees against your bank statement. A paper enters review only once its
        payment is confirmed.
      </p>

      {/* ── Reconciliation figures ── */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        <Tile
          label="सत्यापन हेतु / Awaiting"
          value={summary ? String(summary.awaitingCount) : "—"}
          tone={summary && summary.awaitingCount > 0 ? "amber" : "plain"}
        />
        <Tile
          label={`${summary?.staleAfterDays ?? 3}+ दिन प्रतीक्षारत / Waiting too long`}
          value={summary ? String(summary.staleCount) : "—"}
          tone={summary && summary.staleCount > 0 ? "red" : "plain"}
        />
        <Tile
          label="इस माह पुष्ट / Confirmed this month"
          value={summary ? inr(summary.confirmedThisMonthPaise) : "—"}
          sub={summary ? `${summary.confirmedThisMonthCount} भुगतान / payments` : undefined}
          tone="green"
        />
        <Tile
          label="इस वर्ष पुष्ट / Confirmed this year"
          value={summary ? inr(summary.confirmedThisYearPaise) : "—"}
          sub={summary ? `${summary.confirmedThisYearCount} भुगतान / payments` : undefined}
          tone="plain"
        />
      </div>

      {summary && summary.staleCount > 0 && (
        <div className="mb-6 flex items-start gap-2 rounded-md border border-red-200 bg-red-50 p-3 text-sm text-red-800">
          <Clock className="h-4 w-4 mt-0.5 shrink-0" />
          <span>
            {summary.staleCount} भुगतान {summary.staleAfterDays} दिन से अधिक प्रतीक्षा में हैं — ये
            लेखक भुगतान कर चुके हैं और उत्तर की प्रतीक्षा कर रहे हैं।
            <br />
            {summary.staleCount} payment{summary.staleCount === 1 ? "" : "s"} have been waiting
            more than {summary.staleAfterDays} days. These authors have paid and heard nothing.
          </span>
        </div>
      )}

      {/* ── Filters ── */}
      <div className="flex flex-wrap items-center gap-2 mb-4">
        {FILTERS.map((f) => (
          <button
            key={f.value || "all"}
            onClick={() => {
              setStatus(f.value);
              setPage(0);
            }}
            className={cn(
              "rounded-md px-3 py-1.5 text-xs font-medium transition border",
              status === f.value
                ? "bg-indigo-600 text-white border-indigo-600"
                : "bg-white text-gray-600 border-gray-200 hover:bg-gray-50"
            )}
          >
            {f.hi} / {f.en}
          </button>
        ))}

        <form
          className="ml-auto flex items-center gap-2"
          onSubmit={(e) => {
            e.preventDefault();
            setSearch(searchInput.trim());
            setPage(0);
          }}
        >
          <div className="relative">
            <Search className="absolute left-2 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
            <input
              value={searchInput}
              onChange={(e) => setSearchInput(e.target.value)}
              placeholder="UTR, नाम, ईमेल, शोधपत्र / UTR, name, email, paper"
              className="w-72 rounded-md border border-gray-300 pl-8 pr-3 py-1.5 text-sm focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500"
            />
          </div>
          <button
            type="submit"
            className="rounded-md bg-gray-900 px-3 py-1.5 text-xs font-medium text-white hover:bg-gray-700"
          >
            खोजें / Search
          </button>
        </form>
      </div>

      {/* ── Table ── */}
      <div className="overflow-x-auto rounded-lg border border-gray-200 bg-white">
        <table className="w-full text-sm">
          <thead className="bg-gray-50 text-left text-xs uppercase tracking-wide text-gray-500">
            <tr>
              <th className="px-4 py-3 font-medium">लेखक / Author</th>
              <th className="px-4 py-3 font-medium">शोधपत्र / Paper</th>
              <th className="px-4 py-3 font-medium">रेफ़रेंस / Reference</th>
              <th className="px-4 py-3 font-medium">राशि / Amount</th>
              <th className="px-4 py-3 font-medium">स्थिति / Status</th>
              <th className="px-4 py-3 font-medium text-right">कार्रवाई / Action</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-100">
            {listQuery.isLoading && (
              <tr>
                <td colSpan={6} className="px-4 py-10 text-center text-gray-400">
                  <Loader2 className="h-5 w-5 animate-spin inline" />
                </td>
              </tr>
            )}

            {!listQuery.isLoading && rows.length === 0 && (
              <tr>
                <td colSpan={6} className="px-4 py-10 text-center text-gray-400">
                  {status === "AWAITING_CONFIRMATION"
                    ? "सत्यापन हेतु कोई भुगतान नहीं — सब निपट गया / Nothing waiting to be verified"
                    : "कोई भुगतान नहीं मिला / No payments found"}
                </td>
              </tr>
            )}

            {rows.map((p) => (
              <tr key={p.id} className={cn("align-top", p.stale && "bg-red-50/50")}>
                <td className="px-4 py-3">
                  <div className="font-medium text-gray-900">
                    {p.authorNameHi || p.authorNameEn || "—"}
                  </div>
                  <div className="text-xs text-gray-500">{p.authorEmail}</div>
                  {p.authorPhone && <div className="text-xs text-gray-400">{p.authorPhone}</div>}
                </td>

                <td className="px-4 py-3">
                  <div className="font-mono text-xs text-gray-700">{p.paperReferenceNo || "—"}</div>
                  <div className="text-xs text-gray-500 max-w-xs truncate">
                    {p.paperTitleHi || p.paperTitleEn}
                  </div>
                </td>

                <td className="px-4 py-3">
                  {p.reference ? (
                    <>
                      <div className="flex items-center gap-1">
                        <span className="font-mono text-sm text-gray-900">{p.reference}</span>
                        <button
                          title="कॉपी करें / Copy"
                          onClick={() => {
                            navigator.clipboard?.writeText(p.reference ?? "");
                            toast.success("कॉपी हो गया / Copied");
                          }}
                          className="text-gray-400 hover:text-gray-700"
                        >
                          <Copy className="h-3.5 w-3.5" />
                        </button>
                      </div>
                      <div className="text-xs text-gray-400">{when(p.declaredAt)}</div>
                      {p.payerNote && (
                        <div className="text-xs text-gray-500 italic max-w-xs">{p.payerNote}</div>
                      )}
                      {p.duplicateReference && (
                        <div className="mt-1 inline-flex items-center gap-1 rounded bg-red-100 px-1.5 py-0.5 text-xs font-medium text-red-700">
                          <AlertTriangle className="h-3 w-3" />
                          यह रेफ़रेंस दोबारा दिया गया है / Reference claimed twice
                        </div>
                      )}
                    </>
                  ) : (
                    <span className="text-xs text-gray-400">
                      लेखक ने अभी विवरण नहीं दिया / Not declared yet
                    </span>
                  )}
                </td>

                <td className="px-4 py-3 whitespace-nowrap">
                  <div className="font-medium text-gray-900">{inr(p.totalPaise)}</div>
                  <div className="text-xs text-gray-400">
                    {inr(p.amountPaise)} + {inr(p.gstPaise)} GST
                  </div>
                </td>

                <td className="px-4 py-3">
                  <span
                    className={cn(
                      "inline-block rounded-full px-2 py-0.5 text-xs font-medium",
                      STATUS_STYLE[p.status].cls
                    )}
                  >
                    {STATUS_STYLE[p.status].hi} / {STATUS_STYLE[p.status].en}
                  </span>
                  {p.stale && (
                    <div className="mt-1 text-xs font-medium text-red-600">
                      प्रतीक्षा में / waiting
                    </div>
                  )}
                  {p.confirmedAt && (
                    <div className="mt-1 text-xs text-gray-500">
                      {when(p.confirmedAt)}
                      {p.confirmedByName && <> · {p.confirmedByName}</>}
                    </div>
                  )}
                  {p.rejectionReason && (
                    <div className="mt-1 text-xs text-red-600 max-w-xs">{p.rejectionReason}</div>
                  )}
                </td>

                <td className="px-4 py-3 text-right">
                  {p.status === "AWAITING_CONFIRMATION" ? (
                    <div className="flex justify-end gap-2">
                      <button
                        disabled={confirmMutation.isPending}
                        onClick={() => confirmMutation.mutate(p.id)}
                        className="inline-flex items-center gap-1 rounded-md bg-green-600 px-2.5 py-1.5 text-xs font-medium text-white hover:bg-green-700 disabled:opacity-50"
                      >
                        <CheckCircle2 className="h-3.5 w-3.5" />
                        मिल गया / Found it
                      </button>
                      <button
                        onClick={() => {
                          setRejecting(p);
                          setReason("");
                        }}
                        className="inline-flex items-center gap-1 rounded-md border border-red-200 px-2.5 py-1.5 text-xs font-medium text-red-700 hover:bg-red-50"
                      >
                        <XCircle className="h-3.5 w-3.5" />
                        नहीं मिला / Not found
                      </button>
                    </div>
                  ) : (
                    <span className="text-xs text-gray-300">—</span>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* ── Paging ── */}
      {(listQuery.data?.totalPages ?? 0) > 1 && (
        <div className="mt-4 flex items-center justify-between text-sm text-gray-500">
          <span>
            {listQuery.data?.totalElements} भुगतान / payments
          </span>
          <div className="flex items-center gap-2">
            <button
              disabled={page === 0}
              onClick={() => setPage((p) => p - 1)}
              className="rounded border border-gray-200 p-1 disabled:opacity-40"
            >
              <ChevronLeft className="h-4 w-4" />
            </button>
            <span>
              {page + 1} / {listQuery.data?.totalPages}
            </span>
            <button
              disabled={page + 1 >= (listQuery.data?.totalPages ?? 1)}
              onClick={() => setPage((p) => p + 1)}
              className="rounded border border-gray-200 p-1 disabled:opacity-40"
            >
              <ChevronRight className="h-4 w-4" />
            </button>
          </div>
        </div>
      )}

      {/* ── Reject dialog ── */}
      {rejecting && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 px-4">
          <div className="w-full max-w-md rounded-xl bg-white p-6 shadow-xl">
            <h2 className="text-lg font-semibold text-gray-900 mb-1">
              भुगतान अस्वीकार करें / Reject payment
            </h2>
            <p className="text-sm text-gray-500 mb-4">
              {rejecting.authorNameHi || rejecting.authorNameEn} · {inr(rejecting.totalPaise)} ·{" "}
              <span className="font-mono">{rejecting.reference}</span>
            </p>

            {/* Required, and it goes straight to the author — a bare rejection
                leaves them re-entering the same reference forever. */}
            <label className="block text-sm font-medium text-gray-700 mb-1">
              कारण (लेखक को भेजा जाएगा) / Reason (sent to the author)
            </label>
            <textarea
              value={reason}
              onChange={(e) => setReason(e.target.value)}
              rows={3}
              autoFocus
              placeholder="जैसे: 5 सितंबर को इस राशि का कोई क्रेडिट नहीं मिला / e.g. No credit for this amount on 5 Sep"
              className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm focus:border-indigo-500 focus:outline-none focus:ring-1 focus:ring-indigo-500"
            />

            <div className="mt-4 flex justify-end gap-2">
              <button
                onClick={() => setRejecting(null)}
                className="rounded-md border border-gray-200 px-3 py-2 text-sm text-gray-600 hover:bg-gray-50"
              >
                रद्द / Cancel
              </button>
              <button
                disabled={!reason.trim() || rejectMutation.isPending}
                onClick={() =>
                  rejectMutation.mutate({ id: rejecting.id, reason: reason.trim() })
                }
                className="inline-flex items-center gap-1 rounded-md bg-red-600 px-3 py-2 text-sm font-medium text-white hover:bg-red-700 disabled:opacity-50"
              >
                {rejectMutation.isPending && <Loader2 className="h-4 w-4 animate-spin" />}
                अस्वीकार करें / Reject
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

function Tile({
  label,
  value,
  sub,
  tone,
}: {
  label: string;
  value: string;
  sub?: string;
  tone: "plain" | "amber" | "red" | "green";
}) {
  const tones = {
    plain: "border-gray-200 bg-white",
    amber: "border-amber-200 bg-amber-50",
    red: "border-red-200 bg-red-50",
    green: "border-green-200 bg-green-50",
  };
  return (
    <div className={cn("rounded-lg border p-4", tones[tone])}>
      <div className="text-xs text-gray-500 leading-snug">{label}</div>
      <div className="mt-1 text-xl font-semibold text-gray-900">{value}</div>
      {sub && <div className="text-xs text-gray-400">{sub}</div>}
    </div>
  );
}
