import { cn } from "@/lib/utils";
import { formatCurrency } from "@/lib/format-currency";
import { formatDateShort } from "@/lib/format-date";
import {
  STATEMENT_INK_MUTED,
  STATEMENT_RULE,
  STATEMENT_RULE_LIGHT,
} from "@/components/ui/statement-primitives";

/**
 * StatementTransactionTable - WealthX DS (L3 Organism)
 *
 * The transaction ledger printed on a generated statement. Static and
 * print-density by design - no sorting, filtering, or row actions. For the
 * interactive screen equivalent see `DashboardTransactionsTable`.
 *
 * One column shape for every account type, matching the
 * `Sample_Open_Banking_statement_*` references: Date · Transaction · Debit ·
 * Credit · Balance. Loan and card statements run the same ledger with signed
 * (negative) balances - a repayment is a credit, an interest charge a debit.
 *
 * Layer: L3 Organism
 */

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

export interface StatementTransaction {
  id: string;
  /** ISO date string. */
  date: string;
  description: string;
  /** Signed movement - positive is a credit, negative a debit. */
  amount: number;
  /** Running account balance after this transaction - signed, negative when owing. */
  balance?: number;
}

export interface StatementTransactionTableProps {
  transactions: StatementTransaction[];
  /** Balance carried into the period - rendered as the first row. */
  openingBalance?: number;
  /** Balance at the end of the period - rendered as the closing row. */
  closingBalance?: number;
  openingLabel?: string;
  closingLabel?: string;
  /** Optional heading above the table. */
  title?: string;
  /** Shown when `transactions` is empty. */
  emptyMessage?: string;
  className?: string;
}

// ---------------------------------------------------------------------------
// StatementTransactionTable
// ---------------------------------------------------------------------------

export function StatementTransactionTable({
  transactions,
  openingBalance,
  closingBalance,
  openingLabel = "Opening balance",
  closingLabel = "Closing balance",
  title,
  emptyMessage = "No transactions for this statement period.",
  className,
}: StatementTransactionTableProps) {
  return (
    <div
      data-slot="statement-transaction-table"
      className={cn("flex flex-col gap-3", className)}
    >
      {title && <span className="text-label-medium">{title}</span>}

      <table className="w-full table-fixed border-collapse">
        <thead>
          <tr className={cn("border-b", STATEMENT_RULE)}>
            <th className="w-[14%] pb-2 text-left text-label-small">Date</th>
            <th className="pb-2 text-left text-label-small">Transaction</th>
            <th className="w-[13%] pb-2 text-right text-label-small">Debit</th>
            <th className="w-[13%] pb-2 text-right text-label-small">Credit</th>
            <th className="w-[16%] pb-2 text-right text-label-small">
              Balance
            </th>
          </tr>
        </thead>

        <tbody>
          {openingBalance !== undefined && (
            <tr className={cn("border-b", STATEMENT_RULE_LIGHT)}>
              <td className="py-2 text-label-small" colSpan={4}>
                {openingLabel}
              </td>
              <td className="py-2 text-right text-label-small">
                {formatCurrency(openingBalance, { decimals: 2 })}
              </td>
            </tr>
          )}

          {transactions.length === 0 ? (
            <tr>
              <td
                colSpan={5}
                className={cn(
                  "py-8 text-center text-body-small",
                  STATEMENT_INK_MUTED,
                )}
              >
                {emptyMessage}
              </td>
            </tr>
          ) : (
            transactions.map((transaction) => {
              const isDebit = transaction.amount < 0;
              return (
                <tr
                  key={transaction.id}
                  className={cn("border-b align-top", STATEMENT_RULE_LIGHT)}
                >
                  <td className={cn("py-2 text-body-small", STATEMENT_INK_MUTED)}>
                    {formatDateShort(transaction.date)}
                  </td>
                  <td className="py-2 pr-4 text-body-small break-words">
                    {transaction.description}
                  </td>
                  <td className="py-2 text-right text-body-small">
                    {isDebit
                      ? formatCurrency(Math.abs(transaction.amount), {
                          decimals: 2,
                        })
                      : ""}
                  </td>
                  <td className="py-2 text-right text-body-small">
                    {isDebit
                      ? ""
                      : formatCurrency(transaction.amount, { decimals: 2 })}
                  </td>
                  <td className="py-2 text-right text-body-small">
                    {transaction.balance !== undefined
                      ? formatCurrency(transaction.balance, { decimals: 2 })
                      : ""}
                  </td>
                </tr>
              );
            })
          )}

          {closingBalance !== undefined && (
            <tr className={cn("border-b-2", STATEMENT_RULE)}>
              <td className="py-2 text-label-small" colSpan={4}>
                {closingLabel}
              </td>
              <td className="py-2 text-right text-label-small">
                {formatCurrency(closingBalance, { decimals: 2 })}
              </td>
            </tr>
          )}
        </tbody>
      </table>
    </div>
  );
}
