// Trial balance tab, labeled "Accountant view" — Task 9. This is the ONE
// place in the whole UI allowed to say "Debit"/"Credit" (CLAUDE.md §9: "no
// debit/credit words anywhere EXCEPT the trial-balance accountant view").
// GET /api/c/reports/trial-balance?asOf= returns raw, debit-positive figures
// straight from trial_balance() — no sign flip here, unlike the other two
// tabs (see server/src/reports.ts's file header comment on the two report
// shapes).

import { useState } from "react";
import { useCompany } from "../lib/company";
import { useApiGet } from "../lib/useApiGet";
import { fmtMoney } from "../lib/money";
import { todayIso } from "../lib/date";
import { ErrorBanner } from "../components/ErrorBanner";
import { AccountLink } from "./AccountLink";

interface TbRow {
  accountId: string;
  code: string;
  name: string;
  type: string;
  debit: string;
  credit: string;
  balance: string;
}

interface TbData {
  asOf: string | null;
  rows: TbRow[];
  totals: { debit: string; credit: string };
}

export function TrialBalanceReport({ onSelectAccount }: { onSelectAccount: (accountId: string) => void }) {
  const { selectedCompanyId } = useCompany();
  const [asOf, setAsOf] = useState(todayIso);

  const path = `/api/c/reports/trial-balance?asOf=${asOf}`;
  const { data, loading, error, retry } = useApiGet<TbData>(path, selectedCompanyId);

  return (
    <div>
      <p className="sub" style={{ margin: "0 0 12px" }}>
        The accountant's view of the ledger — every account with its raw debit and credit totals. This is the one
        report in the app that uses those words; everywhere else you'll see plain English.
      </p>
      <div className="report-toolbar">
        <label>
          As of
          <input type="date" value={asOf} onChange={(ev) => setAsOf(ev.target.value)} />
        </label>
      </div>

      {error && <ErrorBanner message={error} onRetry={retry} />}
      {loading && !data && <p className="msg-inline">Loading&hellip;</p>}
      {!loading && !error && data && data.rows.length === 0 && (
        <div className="empty-state">No accounts have activity as of this date.</div>
      )}

      {data && data.rows.length > 0 && (
        <div className="card">
          <table>
            <thead>
              <tr>
                <th>Code</th>
                <th>Account</th>
                <th className="num">Debit</th>
                <th className="num">Credit</th>
                <th className="num">Balance</th>
              </tr>
            </thead>
            <tbody>
              {data.rows.map((row) => (
                <tr key={row.accountId}>
                  <td>{row.code}</td>
                  <td>
                    <AccountLink id={row.accountId} name={row.name} onSelect={onSelectAccount} />
                  </td>
                  <td className="num">{fmtMoney(row.debit)}</td>
                  <td className="num">{fmtMoney(row.credit)}</td>
                  <td className="num">{fmtMoney(row.balance)}</td>
                </tr>
              ))}
              <tr className="total-row">
                <td colSpan={2}>Totals</td>
                <td className="num">{fmtMoney(data.totals.debit)}</td>
                <td className="num">{fmtMoney(data.totals.credit)}</td>
                <td className="num" />
              </tr>
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
