import Link from "next/link";
import { ArrowLeft, FileText, Pencil } from "lucide-react";
import { customerApi } from "@/lib/api/customer";
import { requireServerToken } from "@/lib/auth/server";
import type { ApiCreditRequest } from "@/lib/api/types";
import { formatCurrency, formatDateTime } from "@/lib/utils";

type PageProps = {
  params: Promise<{ id: string }>;
};

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) : "—";
}

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";
}

async function loadCreditRequest(token: string, id: number) {
  try {
    return { data: await customerApi.creditRequest(token, id), error: null as string | null };
  } catch (e) {
    return { data: null as ApiCreditRequest | null, error: (e as Error).message };
  }
}

/**
 * Nothing on this page is interactive — it is a record and two links — so once
 * the fetch moves to the server it needs no client bundle at all.
 *
 * The client version could not start loading until `useToken` had read the auth
 * cookie inside an effect, which only runs after hydration. Reading the cookie
 * during SSR removes that waterfall: the detail arrives in the first HTML
 * response instead of a spinner that is later swapped out.
 */
export default async function CreditRequestDetailPage({ params }: PageProps) {
  const { id } = await params;
  const token = await requireServerToken(`/credit-request/${id}`);

  const { data, error: err } = await loadCreditRequest(token, Number(id));

  if (err) return <div className="rounded-xl bg-red-50 p-6 text-red-700 ring-1 ring-red-100">{err}</div>;
  if (!data) return null;

  const code = statusCode(data);
  // `submitted` resolves uploads to links; older API builds only had form_data.
  const submitted =
    data.submitted ??
    ((data.form_data as Array<{ label: string; value: string }>) || []).map((f) => ({
      label: f.label,
      type: "text",
      value: f.value,
      url: null as string | null,
    }));

  return (
    <div className="space-y-4">
      <Link
        href="/credit-request"
        className="inline-flex items-center gap-1 text-sm text-gray-600 hover:text-[#CC1414]"
      >
        <ArrowLeft className="h-4 w-4" /> Back to credit requests
      </Link>

      <div className="rounded-xl bg-white p-6 shadow-sm ring-1 ring-gray-100">
        <div className="flex flex-wrap items-start justify-between gap-3">
          <div>
            <h1 className="text-2xl font-bold text-gray-900">{readTitle(data.document_type_title)}</h1>
            <p className="text-sm text-gray-500">Reference: {data.reference_number ?? `#${data.id}`}</p>
            <p className="text-sm text-gray-500">
              Submitted: {formatDateTime(data.created_at)}
            </p>
            {data.amount ? (
              <p className="mt-2 text-sm text-gray-700">
                Credit limit requested: <span className="font-semibold text-gray-900">{formatCurrency(data.amount)}</span>
                {data.tenure_days ? <> for <span className="font-semibold text-gray-900">{data.tenure_days} days</span></> : null}
              </p>
            ) : null}
          </div>
          <div className="flex flex-col items-end gap-2">
            <span
              className={`rounded-full px-3 py-1 text-xs font-semibold uppercase ring-1 ring-inset ${statusTone(code)}`}
            >
              {statusLabel(code)}
            </span>
            {code === "pending" && (
              <Link
                href={`/credit-request/${data.id}/edit`}
                className="inline-flex items-center gap-1 rounded-lg border border-gray-200 px-3 py-1.5 text-xs font-medium text-gray-700 hover:border-[#CC1414] hover:text-[#CC1414]"
              >
                <Pencil className="h-3.5 w-3.5" /> Edit
              </Link>
            )}
          </div>
        </div>
      </div>

      {submitted.length > 0 && (
        <div className="rounded-xl bg-white p-6 shadow-sm ring-1 ring-gray-100">
          <h2 className="mb-3 text-sm font-semibold uppercase tracking-wide text-gray-500">
            Application Details
          </h2>
          <dl className="grid grid-cols-1 gap-4 sm:grid-cols-2">
            {submitted.map((f, i) => (
              <div key={i}>
                <dt className="text-xs uppercase text-gray-500">{f.label}</dt>
                <dd className="mt-1 text-sm font-medium text-gray-900 break-words">
                  {f.url ? (
                    <a href={f.url} target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-1 text-[#CC1414] hover:underline">
                      <FileText className="h-4 w-4" aria-hidden /> View document
                    </a>
                  ) : f.type === "file" ? (
                    <span className="text-gray-500">Not uploaded</span>
                  ) : (
                    f.value || "—"
                  )}
                </dd>
              </div>
            ))}
          </dl>
        </div>
      )}

      <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
        <Card title="Notes">{data.notes || "—"}</Card>
        <Card title="Description">{data.description || "—"}</Card>
      </div>
    </div>
  );
}

function Card({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <div className="rounded-xl bg-white p-5 shadow-sm ring-1 ring-gray-100">
      <div className="mb-2 text-xs font-semibold uppercase tracking-wide text-gray-500">{title}</div>
      <div className="break-words text-sm text-gray-700">{children}</div>
    </div>
  );
}
