// A/R aging tab — AR Task 6. GET /api/c/reports/aging?asOf= (server/src/
// payments.ts) already does every bit of bucketing and summing in SQL — this
// component only formats and displays. asOf defaults to today; picking a
// past date reconstructs history as it stood that day (document_only
// invoices included, same as everywhere else AR touches "what's open").
// Customer rows link to #invoices pre-filtered to that customer, same
// sessionStorage handoff CustomersScreen.tsx's balance links already use.

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

interface AgingBuckets {
  current: string;
  d1_30: string;
  d31_60: string;
  d61_90: string;
  d90_plus: string;
}

interface AgingCustomerRow {
  customerId: string;
  name: string;
  buckets: AgingBuckets;
  credits: string;
  total: string;
}

interface AgingData {
  asOf: string;
  customers: AgingCustomerRow[];
  totals: AgingBuckets & { credits: string; grand: string };
}

function buildPath(asOf: string): string {
  const params = new URLSearchParams();
  if (asOf) params.set("asOf", asOf);
  const qs = params.toString();
  return `/api/c/reports/aging${qs ? `?${qs}` : ""}`;
}

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

  const path = buildPath(asOf);
  const { data, loading, error, retry } = useApiGet<AgingData>(path, selectedCompanyId);

  function goToCustomerInvoices(customerId: string) {
    setPendingCustomerFilter(customerId);
    navigate("invoices");
  }

  const isToday = asOf === todayIso();

  return (
    <div>
      <div className="report-toolbar">
        <div className="date-inputs">
          <label>
            As of
            <input type="date" value={asOf} onChange={(ev) => setAsOf(ev.target.value)} />
          </label>
        </div>
      </div>

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

      {data && data.customers.length > 0 && (
        <div className="card">
          <table>
            <thead>
              <tr>
                <th>Customer</th>
                <th className="num">Current</th>
                <th className="num">1&ndash;30</th>
                <th className="num">31&ndash;60</th>
                <th className="num">61&ndash;90</th>
                <th className="num">90+</th>
                <th className="num">Credits</th>
                <th className="num">Total</th>
              </tr>
            </thead>
            <tbody>
              {data.customers.map((c) => (
                <tr key={c.customerId} style={{ cursor: "pointer" }} onClick={() => goToCustomerInvoices(c.customerId)}>
                  <td>
                    <button
                      type="button"
                      className="acct-link"
                      onClick={(ev) => {
                        ev.stopPropagation();
                        goToCustomerInvoices(c.customerId);
                      }}
                    >
                      {c.name}
                    </button>
                  </td>
                  <td className="num">{fmtMoney(c.buckets.current)}</td>
                  <td className="num">{fmtMoney(c.buckets.d1_30)}</td>
                  <td className="num">{fmtMoney(c.buckets.d31_60)}</td>
                  <td className="num">{fmtMoney(c.buckets.d61_90)}</td>
                  <td className="num">{fmtMoney(c.buckets.d90_plus)}</td>
                  <td className="num">{fmtMoney(c.credits)}</td>
                  <td className="num">{fmtMoney(c.total)}</td>
                </tr>
              ))}
              <tr className="total-row">
                <td>Total</td>
                <td className="num">{fmtMoney(data.totals.current)}</td>
                <td className="num">{fmtMoney(data.totals.d1_30)}</td>
                <td className="num">{fmtMoney(data.totals.d31_60)}</td>
                <td className="num">{fmtMoney(data.totals.d61_90)}</td>
                <td className="num">{fmtMoney(data.totals.d90_plus)}</td>
                <td className="num">{fmtMoney(data.totals.credits)}</td>
                <td className="num">{fmtMoney(data.totals.grand)}</td>
              </tr>
            </tbody>
          </table>
        </div>
      )}

      {!isToday && (
        <p className="sub" style={{ marginTop: 10 }}>
          As of a past date, this reconstructs history — what was open on that day.
        </p>
      )}
    </div>
  );
}
