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

/**
 * JS variant. Pass `associationId` to scope to that association's COA system.
 * - `platform` associations read from the Accounting module (`accounting.accounts`).
 * - `zoho` / `buildium` read the public `chart_of_accounts`.
 * When omitted, returns the Buildium (default) set.
 */
export function useCentralChartOfAccounts(associationId) {
  const [accounts, setAccounts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const { system, loading: systemLoading } = useAssociationAccountingSystem(associationId);

  useEffect(() => {
    if (systemLoading) return;
    let isMounted = true;

    const fetchAccounts = async () => {
      setLoading(true);
      setError(null);
      try {
        const rows = await fetchChartOfAccounts(associationId, system);
        // Match prior JS behavior: only active accounts surface here.
        if (isMounted) setAccounts(rows.filter((a) => a.is_active));
      } catch (err) {
        console.error('[useCentralChartOfAccounts] Fetch Error:', err);
        if (isMounted) setError(err.message);
      } finally {
        if (isMounted) setLoading(false);
      }
    };

    fetchAccounts();
    return () => { isMounted = false; };
  }, [associationId, system, systemLoading]);

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