import Link from "next/link";
import { CreditCard, Plus, Eye, Pencil } from "lucide-react";
import { customerApi } from "@/lib/api/customer";
import { requireServerToken } from "@/lib/auth/server";
import type { ApiCreditRequest, PaginationMeta } from "@/lib/api/types";
import NoData from "@/components/ui/NoData";
import { formatCurrency, formatDateShort } from "@/lib/utils";

type PageProps = {
  searchParams: Promise<{ page?: string }>;
};

function statusTone(s: string | null) {
  const map: Record<string, string> = {
    pending: "bg-amber-50 text-amber-700 ring-amber-200",
    approved: "bg-emerald-50 text-emerald-700 ring-emerald-200",
    rejected: "bg-red-50 text-red-700 ring-red-200",
    review: "bg-blue-50 text-blue-700 ring-blue-200",
  };
  return map[(s ?? "").toLowerCase()] ?? "bg-gray-50 text-gray-700 ring-gray-200";
}

function readTitle(t: unknown): string {
  if (typeof t === "string") return t;
  if (t && typeof t === "object") {
    const obj = t as Record<string, string>;
    return obj.en || Object.values(obj)[0] || "—";
  }
  return "—";
}

/** Admin stores "Pending"/"Approved"; the API adds a lower-case `status_code`. */
function statusCode(r: ApiCreditRequest): string {
  return (r.status_code ?? r.status ?? "pending").toLowerCase();
}

function statusLabel(code: string): string {
  return code ? code.charAt(0).toUpperCase() + code.slice(1) : "—";
}

async function loadCreditRequests(token: string, page: number) {
  try {
    return await customerApi.creditRequests(token, { page, perPage: 15 });
  } catch {
    return { data: [] as ApiCreditRequest[], meta: undefined as PaginationMeta | undefined };
  }
}

/**
 * Server-rendered: the token comes from the cookie via `requireServerToken`, so
 * the list is fetched during SSR and the browser receives a populated table.
 *
 * The client version gated its fetch on `useToken`, which reads the same cookie
 * inside an effect — bundle download, parse and hydrate all had to finish before
 * the first request was even made, and the user stared at a spinner throughout.
 * Moving the page number into the URL is what lets the server do the fetching,
 * so this page now ships zero client JS.
 */
export default async function CreditRequestPage({ searchParams }: PageProps) {
  const token = await requireServerToken("/credit-request");
  const sp = await searchParams;

  const page = Math.max(1, Number(sp.page) || 1);

  const { data: list, meta } = await loadCreditRequests(token, page);

  return (
    <div className="space-y-4">
      <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <h1 className="flex items-center gap-2 text-2xl font-bold text-gray-900">
          <CreditCard className="h-6 w-6 text-[#CC1414]" /> Credit Requests
        </h1>
        <Link
          href="/credit-request/new"
          className="inline-flex items-center gap-1.5 rounded-lg bg-[#CC1414] px-4 py-2 text-sm font-medium text-white hover:bg-[#a30f0f]"
        >
          <Plus className="h-4 w-4" /> New Request
        </Link>
      </div>

      {list.length === 0 ? (
        <NoData
          title="No credit requests"
          message="Submit a credit request to apply for working capital from Biznie."
          action={
            <Link
              href="/credit-request/new"
              className="inline-block rounded-lg bg-[#CC1414] px-4 py-2 text-sm font-medium text-white hover:bg-[#a30f0f]"
            >
              Apply for Credit
            </Link>
          }
        />
      ) : (
        <div className="overflow-x-auto rounded-xl bg-white shadow-sm ring-1 ring-gray-100">
          <table className="w-full min-w-[640px] divide-y divide-gray-100 text-sm">
            <thead className="bg-gray-50 text-left text-xs font-semibold uppercase tracking-wide text-gray-500">
              <tr>
                <th className="px-4 py-3">Reference</th>
                <th className="px-4 py-3">Facility</th>
                <th className="px-4 py-3">Amount</th>
                <th className="px-4 py-3">Status</th>
                <th className="px-4 py-3">Submitted</th>
                <th className="px-4 py-3"></th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-100">
              {list.map((r) => (
                <tr key={r.id} className="hover:bg-gray-50">
                  <td className="whitespace-nowrap px-4 py-3 font-medium text-gray-900">
                    {r.reference_number ?? `#${r.id}`}
                  </td>
                  <td className="px-4 py-3 text-gray-700">{readTitle(r.document_type_title)}</td>
                  <td className="whitespace-nowrap px-4 py-3 text-gray-700">
                    {r.amount ? formatCurrency(r.amount) : "—"}
                    {r.tenure_days ? <span className="block text-xs text-gray-500">{r.tenure_days} days</span> : null}
                  </td>
                  <td className="px-4 py-3">
                    <span
                      className={`inline-flex rounded-full px-2.5 py-0.5 text-xs font-medium ring-1 ring-inset ${statusTone(
                        statusCode(r)
                      )}`}
                    >
                      {statusLabel(statusCode(r))}
                    </span>
                  </td>
                  <td className="px-4 py-3 text-gray-700">
                    {formatDateShort(r.created_at)}
                  </td>
                  <td className="px-4 py-3 text-right">
                    <div className="flex items-center justify-end gap-2">
                      <Link
                        href={`/credit-request/${r.id}`}
                        className="inline-flex items-center gap-1 text-sm font-medium text-[#CC1414] hover:underline"
                      >
                        <Eye className="h-4 w-4" /> View
                      </Link>
                      {statusCode(r) === "pending" && (
                        <Link
                          href={`/credit-request/${r.id}/edit`}
                          className="inline-flex items-center gap-1 text-sm font-medium text-gray-600 hover:text-gray-900"
                        >
                          <Pencil className="h-4 w-4" /> Edit
                        </Link>
                      )}
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {meta && meta.last_page > 1 && (
        <div className="flex flex-wrap items-center justify-between gap-3 rounded-xl bg-white px-4 py-3 shadow-sm ring-1 ring-gray-100">
          <span className="min-w-0 truncate text-sm text-gray-500">
            Page {meta.current_page} of {meta.last_page} · {meta.total} total
          </span>
          {/* Plain links: no client JS needed for paging. */}
          <div className="flex gap-2">
            {page > 1 ? (
              <Link
                href={`/credit-request?page=${page - 1}`}
                className="rounded-md border px-4 py-2 text-sm hover:bg-gray-50"
              >
                Prev
              </Link>
            ) : (
              <span className="rounded-md border px-4 py-2 text-sm opacity-50">Prev</span>
            )}
            {page < meta.last_page ? (
              <Link
                href={`/credit-request?page=${page + 1}`}
                className="rounded-md border px-4 py-2 text-sm hover:bg-gray-50"
              >
                Next
              </Link>
            ) : (
              <span className="rounded-md border px-4 py-2 text-sm opacity-50">Next</span>
            )}
          </div>
        </div>
      )}
    </div>
  );
}
