import Link from "next/link";
import { customerApi } from "@/lib/api/customer";
import { requireServerToken } from "@/lib/auth/server";
import type { ApiWalletSummary, ApiWalletTransaction } from "@/lib/api/types";
import { Wallet, ArrowDownLeft, ArrowUpRight } from "lucide-react";
import { formatDateShort, formatDateTime } from "@/lib/utils";

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

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


const TABS = ["cash", "credit"] as const;
type Tab = (typeof TABS)[number];

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

async function loadSummary(token: string): Promise<ApiWalletSummary | null> {
  try {
    return await customerApi.walletSummary(token);
  } catch {
    return null;
  }
}

async function loadTransactions(token: string, tab: Tab): Promise<ApiWalletTransaction[]> {
  try {
    const fn = tab === "cash" ? customerApi.walletCash : customerApi.walletCredit;
    const r = await fn(token, { perPage: 30 });
    return r.data;
  } catch {
    return [];
  }
}

/**
 * Server-rendered wallet.
 *
 * The client version ran two effects — one for the balances, one for the
 * selected tab's transactions — which the browser fired only after hydration
 * and which raced each other into separate state updates. Here both requests
 * are issued together with `Promise.all`, so the page costs one round trip
 * rather than two, and the selected tab lives in the URL so the server knows
 * which list to fetch before rendering anything.
 */
export default async function WalletPage({ searchParams }: PageProps) {
  const token = await requireServerToken("/wallet");
  const sp = await searchParams;

  const tab: Tab = sp.tab === "credit" ? "credit" : "cash";

  // Independent requests: neither result feeds the other, so they go out at once.
  const [summary, list] = await Promise.all([loadSummary(token), loadTransactions(token, tab)]);

  return (
    <div className="space-y-4">
      <h1 className="text-2xl font-bold text-gray-900">Wallet</h1>

      <div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
        <BalanceCard label="Cash Balance" value={summary?.cash_balance ?? 0} tone="bg-emerald-50 text-emerald-600" />
        <BalanceCard label="Credit Balance" value={summary?.credit_balance ?? 0} tone="bg-blue-50 text-blue-600" />
        <BalanceCard
          label="Assigned Credit"
          value={summary?.assign_credit_balance ?? 0}
          tone="bg-purple-50 text-purple-600"
          note={<CreditLimitNote summary={summary} />}
        />
      </div>

      <div className="rounded-xl bg-white shadow-sm ring-1 ring-gray-100">
        {/* Plain links: switching tabs is a navigation, not client state. */}
        <div className="flex border-b border-gray-100">
          {TABS.map((t) => (
            <Link
              key={t}
              href={`/wallet?tab=${t}`}
              className={`px-5 py-3 text-sm font-medium capitalize transition ${
                tab === t ? "border-b-2 border-[#CC1414] text-[#CC1414]" : "text-gray-500 hover:text-gray-700"
              }`}
            >
              {t} Transactions
            </Link>
          ))}
        </div>

        <div className="p-4">
          {list.length === 0 ? (
            <div className="py-10 text-center text-gray-500">No transactions yet.</div>
          ) : (
            <ul className="divide-y divide-gray-100">
              {list.map((t) => (
                <li key={t.id} className="flex items-center gap-4 py-3">
                  <span className={`flex h-9 w-9 items-center justify-center rounded-full ${t.status === "credit" ? "bg-emerald-50 text-emerald-600" : "bg-red-50 text-red-600"}`}>
                    {t.status === "credit" ? <ArrowDownLeft className="h-4 w-4" /> : <ArrowUpRight className="h-4 w-4" />}
                  </span>
                  <div className="min-w-0 flex-1">
                    <div className="truncate text-sm font-medium text-gray-900">{t.description ?? t.transaction_status ?? "—"}</div>
                    <div className="text-xs text-gray-500">
                      {t.transaction_id} {t.mode && `· ${t.mode}`} {t.created_at && `· ${formatDateTime(t.created_at)}`}
                    </div>
                  </div>
                  <div className={`text-sm font-semibold ${t.status === "credit" ? "text-emerald-600" : "text-red-600"}`}>
                    {t.status === "credit" ? "+" : "−"} {fmtINR(t.amount)}
                  </div>
                </li>
              ))}
            </ul>
          )}
        </div>
      </div>
    </div>
  );
}

/**
 * A limit with no story behind it read as a mistake (B30): say whether it came
 * from an approved credit request or was set by the credit team.
 */
function CreditLimitNote({ summary }: { summary: ApiWalletSummary | null }) {
  const src = summary?.credit_limit_source;
  if (!summary || (summary.assign_credit_balance ?? 0) <= 0) {
    return (
      <Link href="/credit-request/new" className="font-medium text-[#CC1414] hover:underline">
        Apply for a credit limit
      </Link>
    );
  }
  if (src?.via === "request" && src.request_id) {
    return (
      <>
        Approved on request{" "}
        <Link href={`/credit-request/${src.request_id}`} className="font-medium text-[#CC1414] hover:underline">
          {src.reference ?? `#${src.request_id}`}
        </Link>
        {src.approved_at ? ` · ${formatDateShort(src.approved_at)}` : ""}
        {src.tenure_days ? ` · ${src.tenure_days}-day credit` : ""}
      </>
    );
  }
  return <>Set by the Biznie credit team</>;
}

function BalanceCard({ label, value, tone, note }: { label: string; value: number; tone: string; note?: React.ReactNode }) {
  return (
    <div className="rounded-xl bg-white p-5 shadow-sm ring-1 ring-gray-100">
      <div className="flex items-center justify-between">
        <span className="text-xs font-medium uppercase tracking-wide text-gray-500">{label}</span>
        <span className={`flex h-9 w-9 items-center justify-center rounded-lg ${tone}`}>
          <Wallet className="h-5 w-5" />
        </span>
      </div>
      <div className="mt-3 text-2xl font-bold text-gray-900">{fmtINR(value)}</div>
      {note && <div className="mt-1 text-xs text-gray-500">{note}</div>}
    </div>
  );
}
