// Reports screen — Task 9. Tabs: Profit & loss (default), Balance sheet,
// Trial balance ("Accountant view" — the one place CLAUDE.md §9 allows
// "Debit"/"Credit" words), A/R aging, A/P aging, and — ONLY for companies
// with sales tax turned on — Sales tax (Task 3 of
// docs/superpowers/plans/2026-08-02-sales-tax.md; the tab is entirely absent
// otherwise, per the spec's "invisible until enabled"). Every account row
// across the tabs drills through to #/account/:id via onSelectAccount, which
// App.tsx wires to navigate().

import { useEffect, useState } from "react";
import { useCompany } from "./lib/company";
import { useApiGet } from "./lib/useApiGet";
import type { NavTarget } from "./lib/useHashView";
import { ProfitLossReport } from "./reports/ProfitLoss";
import { BalanceSheetReport } from "./reports/BalanceSheet";
import { TrialBalanceReport } from "./reports/TrialBalance";
import { AgingReport } from "./reports/Aging";
import { ApAgingReport } from "./reports/ApAging";
import { SalesTaxReport } from "./reports/SalesTax";
import { InventoryValuationReport } from "./reports/InventoryValuation";
import { ItemProfitabilityReport } from "./reports/ItemProfitability";
import {
  useItemsPresence, showsInventoryValuation, showsItemProfitability,
} from "./items/useItemsPresence";

type Tab =
  | "pnl" | "balance-sheet" | "trial-balance" | "aging" | "ap-aging" | "sales-tax"
  | "inventory-valuation" | "item-profitability";

interface SalesTaxSettings {
  enabled: boolean;
  accountId: string | null;
  accountName: string | null;
}

export function Reports({
  onSelectAccount,
  navigate,
}: {
  onSelectAccount: (accountId: string) => void;
  navigate: (target: NavTarget) => void;
}) {
  const { selectedCompanyId } = useCompany();
  const [tab, setTab] = useState<Tab>("pnl");

  // The Sales tax tab's gate — companies with the toggle off never see it.
  const { data: taxSettings } = useApiGet<SalesTaxSettings>(
    "/api/c/settings/sales-tax", selectedCompanyId,
  );
  const salesTaxEnabled = taxSettings?.enabled === true;

  // The two inventory tabs' gate (Inventory Task 5), same "invisible until it
  // applies" rule — but asked of the COMPANY's stock history, not just its
  // active item list. A company that deactivated its last stocked item is
  // still carrying that stock's value on its balance sheet, and taking the
  // report that explains the balance away (and redirecting off it, below) is
  // hiding live data. showsInventoryValuation/showsItemProfitability own that
  // decision; see items/useItemsPresence.ts for why it is not `hasStockedItems`
  // alone, and note that the SIDEBAR deliberately still uses the narrow one.
  const presence = useItemsPresence(selectedCompanyId);
  const { loading: itemsLoading } = presence;
  const showValuation = showsInventoryValuation(presence);
  const showProfitability = showsItemProfitability(presence);

  // If the company switches (or tax gets turned off, or a company with no
  // stock at all is selected) while one of the gated tabs is showing, fall
  // back to the default rather than rendering a blank pane.
  useEffect(() => {
    if (tab === "sales-tax" && taxSettings && !taxSettings.enabled) {
      setTab("pnl");
    }
  }, [tab, taxSettings]);
  useEffect(() => {
    if (itemsLoading) return;
    if (tab === "inventory-valuation" && !showValuation) setTab("pnl");
    if (tab === "item-profitability" && !showProfitability) setTab("pnl");
  }, [tab, showValuation, showProfitability, itemsLoading]);

  return (
    <div className="wrap">
      <header className="top">
        <h1>Reports</h1>
      </header>

      {!selectedCompanyId ? (
        <p className="msg-inline">Choose a company from the sidebar to see its reports.</p>
      ) : (
        <>
          <div className="tabs">
            <button type="button" aria-current={tab === "pnl" ? "page" : undefined} onClick={() => setTab("pnl")}>
              Profit &amp; loss
            </button>
            <button
              type="button"
              aria-current={tab === "balance-sheet" ? "page" : undefined}
              onClick={() => setTab("balance-sheet")}
            >
              Balance sheet
            </button>
            <button
              type="button"
              aria-current={tab === "trial-balance" ? "page" : undefined}
              onClick={() => setTab("trial-balance")}
            >
              Trial balance (Accountant view)
            </button>
            <button type="button" aria-current={tab === "aging" ? "page" : undefined} onClick={() => setTab("aging")}>
              A/R aging
            </button>
            <button type="button" aria-current={tab === "ap-aging" ? "page" : undefined} onClick={() => setTab("ap-aging")}>
              A/P aging
            </button>
            {salesTaxEnabled && (
              <button
                type="button"
                aria-current={tab === "sales-tax" ? "page" : undefined}
                onClick={() => setTab("sales-tax")}
              >
                Sales tax
              </button>
            )}
            {showValuation && (
              <button
                type="button"
                aria-current={tab === "inventory-valuation" ? "page" : undefined}
                onClick={() => setTab("inventory-valuation")}
              >
                Inventory valuation
              </button>
            )}
            {showProfitability && (
              <button
                type="button"
                aria-current={tab === "item-profitability" ? "page" : undefined}
                onClick={() => setTab("item-profitability")}
              >
                Item profitability
              </button>
            )}
          </div>

          {tab === "pnl" && <ProfitLossReport onSelectAccount={onSelectAccount} navigate={navigate} />}
          {tab === "balance-sheet" && (
            <BalanceSheetReport onSelectAccount={onSelectAccount} navigate={navigate} />
          )}
          {tab === "trial-balance" && <TrialBalanceReport onSelectAccount={onSelectAccount} />}
          {tab === "aging" && <AgingReport navigate={navigate} />}
          {tab === "ap-aging" && <ApAgingReport navigate={navigate} />}
          {tab === "sales-tax" && salesTaxEnabled && <SalesTaxReport navigate={navigate} />}
          {tab === "inventory-valuation" && showValuation && (
            <InventoryValuationReport navigate={navigate} />
          )}
          {tab === "item-profitability" && showProfitability && (
            <ItemProfitabilityReport navigate={navigate} />
          )}
        </>
      )}
    </div>
  );
}
