import Link from "next/link";
import { ArrowLeft, FileText } from "lucide-react";
import { customerApi } from "@/lib/api/customer";
import { requireServerToken } from "@/lib/auth/server";
import type { ApiOrderLedgerEntry, ApiOrderLedgerResponse } from "@/lib/api/types";
import NoData from "@/components/ui/NoData";
import { formatDateTime } from "@/lib/utils";

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

const inr = new Intl.NumberFormat("en-IN", {
  style: "currency",
  currency: "INR",
  maximumFractionDigits: 2,
});


function fmtINR(n: number) {
  return inr.format(n);
}

function fmtDate(s: string | null) {
  if (!s) return "—";
  try {
    return formatDateTime(s);
  } catch {
    return s;
  }
}

type Ledger = { entries: ApiOrderLedgerEntry[]; order: ApiOrderLedgerResponse["order"] | null };

async function loadLedger(token: string, id: number): Promise<Ledger> {
  try {
    const r = await customerApi.orderLedger(token, id);
    return { entries: r.data, order: r.order };
  } catch {
    return { entries: [], order: null };
  }
}

/**
 * Server-rendered ledger. The client version tracked `loading`/`err`/`entries`
 * in three pieces of state purely to narrate a fetch that could not begin until
 * hydration; awaiting the same call during SSR collapses all of it into one
 * value, and the loading branch disappears because there is nothing to wait for
 * by the time the HTML reaches the browser.
 */
export default async function OrderLedgerPage({ params }: PageProps) {
  const { id } = await params;
  const token = await requireServerToken(`/orders/${id}/ledger`);

  const { entries, order } = await loadLedger(token, Number(id));

  return (
    <div className="space-y-4">
      <Link
        href={`/orders/${id}`}
        className="inline-flex items-center gap-1 text-sm text-gray-600 hover:text-[#CC1414]"
      >
        <ArrowLeft className="h-4 w-4" /> Back to order
      </Link>

      <h1 className="flex items-center gap-2 text-2xl font-bold text-gray-900">
        <FileText className="h-6 w-6 text-[#CC1414]" /> Order Ledger
      </h1>

      {order && (
        <div className="grid grid-cols-2 gap-4 rounded-xl bg-white p-5 shadow-sm ring-1 ring-gray-100 md:grid-cols-4">
          <Metric label="Order ID" value={order.order_id ?? order.unique_id ?? "—"} text />
          <Metric label="Total" value={fmtINR(order.total_amount)} />
          <Metric label="Paid" value={fmtINR(order.paid_amount)} tone="text-emerald-600" />
          <Metric label="Due" value={fmtINR(order.due_amount)} tone="text-red-600" />
        </div>
      )}

      {entries.length === 0 ? (
        <NoData title="No ledger entries" message="There are no transactions recorded against this order yet." />
      ) : (
        <div className="overflow-x-auto rounded-xl bg-white shadow-sm ring-1 ring-gray-100">
          <div className="overflow-x-auto">
            <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">#</th>
                  <th className="px-4 py-3">Date</th>
                  <th className="px-4 py-3">Particulars</th>
                  <th className="px-4 py-3">TXN ID</th>
                  <th className="px-4 py-3">Type</th>
                  <th className="px-4 py-3">Mode</th>
                  <th className="px-4 py-3 text-right">Amount</th>
                  <th className="px-4 py-3 text-right">Balance</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-100">
                {entries.map((e, idx) => (
                  <tr key={e.id} className="hover:bg-gray-50">
                    <td className="px-4 py-3 text-gray-500">{idx + 1}</td>
                    <td className="whitespace-nowrap px-4 py-3 text-gray-700">{fmtDate(e.date_time || e.created_at)}</td>
                    <td className="px-4 py-3 text-gray-700">{e.description ?? "—"}</td>
                    <td className="px-4 py-3 text-gray-700">{e.transaction_id ?? "—"}</td>
                    <td className="px-4 py-3 capitalize text-gray-700">{e.type ?? "—"}</td>
                    <td className="px-4 py-3 text-gray-700">{e.payment_mode || e.payment_method || "—"}</td>
                    <td className="px-4 py-3 text-right font-semibold text-gray-900">{fmtINR(e.amount)}</td>
                    <td className="px-4 py-3 text-right text-gray-700">
                      {e.remaining_balance !== null ? fmtINR(e.remaining_balance) : "—"}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  );
}

function Metric({ label, value, tone, text }: { label: string; value: string; tone?: string; text?: boolean }) {
  return (
    <div>
      <div className="text-xs uppercase text-gray-500">{label}</div>
      <div className={`mt-1 truncate ${text ? "text-sm" : "text-lg"} font-semibold tabular-nums ${tone ?? "text-gray-900"}`}>{value}</div>
    </div>
  );
}
