"use client";

import { kes } from "@/components/medora/payroll";
import { cn } from "@/lib/utils";

/*
 * Ledger entries for one document (AC-02, AC-03): what a sale, GRN, bill, payroll run or write-off posted to
 * the General Ledger, shown on the document itself. The posting is made by the server; this only shows it,
 * and says plainly if the lines don't balance, which the server should never allow.
 */

export type EntryLine = { account: string; debit?: number; credit?: number; memo?: string };

export function LedgerEntries({ document, date, status, lines, onOpenAccount }: { document: string; date: string; status: "Posted" | "Will post" | "Reversed"; lines: EntryLine[]; onOpenAccount?: (account: string) => void }) {
  const dr = Math.round(lines.reduce((s, l) => s + (l.debit ?? 0), 0) * 100) / 100;
  const cr = Math.round(lines.reduce((s, l) => s + (l.credit ?? 0), 0) * 100) / 100;
  const balanced = dr === cr;
  return (
    <div className="space-y-2">
      <div className="flex flex-wrap items-baseline justify-between gap-2 text-sm">
        <p>
          <span className="font-medium">{document}</span> <span className="text-muted-foreground">· {date}</span>
        </p>
        <span className={cn("rounded px-1.5 py-0.5 text-[11px] font-medium", status === "Posted" ? "bg-status-success-bg text-status-success-text" : status === "Reversed" ? "bg-muted text-muted-foreground" : "bg-status-info-bg text-status-info-text")}>{status}</span>
      </div>
      <div className="overflow-x-auto rounded-md border border-[var(--color-border-panel)] bg-card">
        <table className="w-full min-w-[520px] text-sm tabular-nums">
          <thead className="bg-[var(--color-bg-surface-subtle)] text-left text-xs text-muted-foreground">
            <tr>
              <th className="px-3 py-2 font-medium">Account</th>
              <th className="px-3 py-2 text-right font-medium">Debit</th>
              <th className="px-3 py-2 text-right font-medium">Credit</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-[var(--color-border-subtle)]">
            {lines.map((l, i) => (
              <tr key={i}>
                <td className={cn("px-3 py-1.5", l.credit && "pl-8")}>
                  {onOpenAccount ? (
                    <button type="button" className="cursor-pointer text-left text-primary underline-offset-4 hover:underline" onClick={() => onOpenAccount(l.account)}>
                      {l.account}
                    </button>
                  ) : (
                    l.account
                  )}
                  {l.memo ? <span className="block text-xs text-muted-foreground">{l.memo}</span> : null}
                </td>
                <td className="px-3 py-1.5 text-right">{l.debit ? kes(l.debit) : ""}</td>
                <td className="px-3 py-1.5 text-right">{l.credit ? kes(l.credit) : ""}</td>
              </tr>
            ))}
          </tbody>
          <tfoot className="border-t-2 border-[var(--color-border-panel)] bg-muted/30 font-semibold">
            <tr>
              <td className="px-3 py-1.5">{balanced ? "Balanced" : <span className="text-status-error-text">Doesn&apos;t balance by {kes(Math.abs(dr - cr))}: report this, it should never happen</span>}</td>
              <td className="px-3 py-1.5 text-right">{kes(dr)}</td>
              <td className="px-3 py-1.5 text-right">{kes(cr)}</td>
            </tr>
          </tfoot>
        </table>
      </div>
    </div>
  );
}
