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

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

/**
 * Rendering moved from the browser to the server, so the timezone has to be
 * pinned: `toLocaleString` used to pick up the visitor's clock, and a server
 * running in UTC would otherwise shift every timestamp for an India-only ledger.
 */

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

async function loadLedger(token: string, id: number) {
  try {
    const r = await sellerApi.orderLedger(token, id);
    return { entries: r.data, order: r.order, err: null as string | null };
  } catch (e) {
    return {
      entries: [] as ApiOrderLedgerEntry[],
      order: null as ApiOrderLedgerResponse["order"] | null,
      err: e instanceof ApiException ? e.message : "Failed to load.",
    };
  }
}

/**
 * One request, resolved during SSR — the old version rendered a spinner, waited
 * for hydration, read the cookie in an effect, and only then asked for the
 * ledger. Nothing on this page is interactive, so none of it needs to be client
 * code; the error state that used to live in `useState` is just a value now.
 */
export default async function SellerOrderLedgerPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;
  const token = await requireServerToken(`/seller/orders/${id}/ledger`);
  await requireRole(["seller"]);

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

  return (
    <div className="space-y-4">
      <Link
        href={`/seller/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]" /> Seller 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={inr.format(order.total_amount)} />
          <Metric label="Paid" value={inr.format(order.paid_amount)} tone="text-emerald-600" />
          <Metric label="Due" value={inr.format(order.due_amount)} tone="text-red-600" />
        </div>
      )}

      {err ? (
        <div className="rounded-xl bg-red-50 p-6 text-red-700 ring-1 ring-red-100">{err}</div>
      ) : entries.length === 0 ? (
        <NoData title="No ledger entries" message="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">
                      {e.type === "credit" ? (
                        <span className="rounded-full bg-emerald-100 px-2 py-0.5 text-xs font-medium text-emerald-700">
                          Credit
                        </span>
                      ) : e.type === "debit" ? (
                        <span className="rounded-full bg-red-100 px-2 py-0.5 text-xs font-medium text-red-700">
                          Debit
                        </span>
                      ) : (
                        <span className="text-xs text-gray-500">{e.type ?? "—"}</span>
                      )}
                    </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">{inr.format(e.amount)}</td>
                    <td className="px-4 py-3 text-right text-gray-700">
                      {e.remaining_balance !== null ? inr.format(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 ${text ? "text-sm" : "text-lg"} font-semibold ${tone ?? "text-gray-900"}`}>{value}</div>
    </div>
  );
}
