// Balance sheet tab — Task 9. GET /api/c/reports/balance-sheet?asOf=
// (server/src/reports.ts) is presentation-signed and already includes the
// "Accumulated profit" line inside `equity` (accountId: null — there's no
// account to drill into for a derived total, so that one row renders as
// plain text instead of an AccountLink).

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";
import type { NavTarget } from "../lib/useHashView";

interface BsRow {
  accountId: string | null;
  code: string | null;
  name: string;
  balance: string;
}

interface BsData {
  asOf: string | null;
  assets: BsRow[];
  assetsTotal: string;
  liabilities: BsRow[];
  liabilitiesTotal: string;
  equity: BsRow[];
  equityTotal: string;
  totalLiabilitiesAndEquity: string;
}

function Row({ row, onSelectAccount }: { row: BsRow; onSelectAccount: (accountId: string) => void }) {
  return (
    <tr>
      <td>
        {row.accountId ? <AccountLink id={row.accountId} name={row.name} onSelect={onSelectAccount} /> : row.name}
      </td>
      <td className="num">{fmtMoney(row.balance)}</td>
    </tr>
  );
}

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

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

  const isEmpty = data && data.assets.length === 0 && data.liabilities.length === 0 && data.equity.length <= 1;

  return (
    <div>
      <div className="report-toolbar">
        <label>
          As of
          <input type="date" value={asOf} onChange={(ev) => setAsOf(ev.target.value)} />
        </label>
        <button
          type="button"
          className="btn print-btn"
          onClick={() => navigate({ view: "print", printType: "balance-sheet", params: { asOf } })}
        >
          Print / Save as PDF
        </button>
      </div>

      {error && <ErrorBanner message={error} onRetry={retry} />}
      {loading && !data && <p className="msg-inline">Loading&hellip;</p>}
      {!loading && !error && isEmpty && <div className="empty-state">Nothing on the books as of this date.</div>}

      {data && !isEmpty && (
        <div className="card">
          <table>
            <thead>
              <tr>
                <th>Account</th>
                <th className="num">Balance</th>
              </tr>
            </thead>
            <tbody>
              <tr className="section-row">
                <td colSpan={2}>What you have</td>
              </tr>
              {data.assets.map((row) => (
                <Row key={row.accountId ?? row.name} row={row} onSelectAccount={onSelectAccount} />
              ))}
              <tr className="total-row">
                <td>Total assets</td>
                <td className="num">{fmtMoney(data.assetsTotal)}</td>
              </tr>

              <tr className="section-row">
                <td colSpan={2}>What you owe</td>
              </tr>
              {data.liabilities.map((row) => (
                <Row key={row.accountId ?? row.name} row={row} onSelectAccount={onSelectAccount} />
              ))}
              <tr className="total-row">
                <td>Total liabilities</td>
                <td className="num">{fmtMoney(data.liabilitiesTotal)}</td>
              </tr>

              <tr className="section-row">
                <td colSpan={2}>Equity</td>
              </tr>
              {data.equity.map((row) => (
                <Row key={row.accountId ?? row.name} row={row} onSelectAccount={onSelectAccount} />
              ))}
              <tr className="total-row">
                <td>Total equity</td>
                <td className="num">{fmtMoney(data.equityTotal)}</td>
              </tr>

              <tr className="net-row">
                <td>Total liabilities &amp; equity</td>
                <td className="num">{fmtMoney(data.totalLiabilitiesAndEquity)}</td>
              </tr>
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
