import { useState, useEffect } from "react";
import { useAssociationAccountingSystem } from "./useAssociationAccountingSystem";
import { fetchChartOfAccounts, type NormalizedAccount } from "@/lib/chartOfAccountsSource";

/**
 * Loads the Chart of Accounts scoped to the association's accounting system.
 * - `platform` associations read from the Accounting module (`accounting.accounts`).
 * - `zoho` / `buildium` read the public `chart_of_accounts`, scoped by system.
 * - If associationId is omitted/null, returns the Buildium (default) set.
 */
export function useCentralChartOfAccounts(associationId?: string | null) {
  const [accounts, setAccounts] = useState<NormalizedAccount[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const { system, loading: systemLoading } = useAssociationAccountingSystem(associationId);

  useEffect(() => {
    if (systemLoading) return;
    let cancelled = false;
    const fetchAccounts = async () => {
      setLoading(true);
      try {
        const rows = await fetchChartOfAccounts(associationId, system);
        if (cancelled) return;
        setAccounts(rows);
        setError(null);
      } catch (fetchError: any) {
        if (cancelled) return;
        console.error("[useCentralChartOfAccounts] Error:", fetchError);
        setError(fetchError?.message ?? "Failed to load accounts");
      } finally {
        if (!cancelled) setLoading(false);
      }
    };

    fetchAccounts();
    return () => {
      cancelled = true;
    };
  }, [associationId, system, systemLoading]);

  return { accounts, loading, error, system };
}
