// Account drill-through — #/account/:id (Task 9 item 2). Reached from any
// report row or the dashboard's BalancePanel. Shows the account's name and a
// paginated (50/page) list of every posted entry that touches it, each row
// framed in plain English via fmtSignedInto() (the API's amountIntoAccount
// is already signed relative to the account's own normal side — see
// server/src/reports.ts's GET /api/c/accounts/:id/entries). Each row drills
// further, to #/entry/:id.

import { useEffect, useState } from "react";
import { useCompany } from "./lib/company";
import { useApiGet } from "./lib/useApiGet";
import { fmtDate } from "./lib/date";
import { fmtSignedInto } from "./lib/money";
import { ErrorBanner } from "./components/ErrorBanner";
import { BackLink } from "./components/BackLink";

const PAGE_SIZE = 50;

interface AccountEntryRow {
  entryId: string;
  entryNo: string;
  date: string;
  who: string | null;
  memo: string | null;
  amountIntoAccount: string;
}

interface AccountEntriesData {
  account: { accountId: string; name: string; type: string };
  total: number;
  entries: AccountEntryRow[];
}

export function AccountEntries({
  accountId,
  onSelectEntry,
}: {
  accountId: string;
  onSelectEntry: (entryId: string) => void;
}) {
  const { selectedCompanyId } = useCompany();
  const [page, setPage] = useState(0);

  // A different account id means a different list — start back at page 1.
  useEffect(() => {
    setPage(0);
  }, [accountId]);

  const offset = page * PAGE_SIZE;
  const path = `/api/c/accounts/${accountId}/entries?limit=${PAGE_SIZE}&offset=${offset}`;
  const { data, loading, error, retry } = useApiGet<AccountEntriesData>(path, selectedCompanyId);

  const total = data?.total ?? 0;
  const showingFrom = total === 0 ? 0 : offset + 1;
  const showingTo = Math.min(offset + PAGE_SIZE, total);

  return (
    <div className="wrap">
      <BackLink label="Back to reports" />

      {error && <ErrorBanner message={error} onRetry={retry} />}
      {loading && !data && <p className="msg-inline">Loading&hellip;</p>}

      {data && (
        <>
          <header className="top">
            <h1>{data.account.name}</h1>
          </header>
          <p className="sub" style={{ marginBottom: 16 }}>
            Every entry that touches this account, most recent first.
          </p>

          {data.entries.length === 0 ? (
            <div className="empty-state">No entries for this account yet.</div>
          ) : (
            <>
              <div className="card act">
                {data.entries.map((row) => (
                  <button
                    key={row.entryId}
                    type="button"
                    className="row"
                    style={{ all: "unset", display: "flex", width: "100%", cursor: "pointer" }}
                    onClick={() => onSelectEntry(row.entryId)}
                  >
                    <div>
                      <div className="who">{row.who ?? row.memo ?? "Journal entry"}</div>
                      <div className="when">
                        {row.who && row.memo ? `${row.memo} · ` : ""}
                        {fmtDate(row.date)}
                      </div>
                    </div>
                    <div className="amt">{fmtSignedInto(row.amountIntoAccount)}</div>
                  </button>
                ))}
              </div>

              <div className="pager">
                <button type="button" disabled={page === 0} onClick={() => setPage((p) => Math.max(0, p - 1))}>
                  Prev
                </button>
                <span className="pager-count">
                  {showingFrom}&ndash;{showingTo} of {total}
                </span>
                <button
                  type="button"
                  disabled={showingTo >= total}
                  onClick={() => setPage((p) => p + 1)}
                >
                  Next
                </button>
              </div>
            </>
          )}
        </>
      )}
    </div>
  );
}
