import { useState, useEffect, useCallback } from 'react';
import { supabase } from '@/integrations/supabase/client';

export function useAccountTree(associationId) {
  const [flatAccounts, setFlatAccounts] = useState([]);
  const [accountTree, setAccountTree] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const fetchAccounts = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      let query = supabase.from('chart_of_accounts').select('*').order('account_number', { ascending: true });
      
      const { data, error: fetchError } = await query;
      if (fetchError) throw fetchError;
      
      setFlatAccounts(data || []);
      setAccountTree(buildTree(data || []));
    } catch (err) {
      console.error('Error fetching accounts:', err);
      setError(err.message);
    } finally {
      setLoading(false);
    }
  }, [associationId]);

  useEffect(() => {
    fetchAccounts();
  }, [fetchAccounts]);

  const buildTree = (accounts) => {
    const accountMap = new Map();
    const roots = [];

    accounts.forEach(acc => {
      accountMap.set(acc.id, { ...acc, children: [] });
    });

    accounts.forEach(acc => {
      if (acc.parent_account_id && accountMap.has(acc.parent_account_id)) {
        accountMap.get(acc.parent_account_id).children.push(accountMap.get(acc.id));
      } else {
        roots.push(accountMap.get(acc.id));
      }
    });

    const sortChildren = (nodes) => {
      nodes.sort((a, b) => (a.account_number || '').localeCompare(b.account_number || ''));
      nodes.forEach(node => {
        if (node.children.length > 0) sortChildren(node.children);
      });
    };
    
    sortChildren(roots);
    return roots;
  };

  const isDescendant = (accountId, targetParentId, allAccounts = flatAccounts) => {
    if (accountId === targetParentId) return true;
    let current = allAccounts.find(a => a.id === targetParentId);
    while (current && current.parent_account_id) {
      if (current.parent_account_id === accountId) return true;
      current = allAccounts.find(a => a.id === current.parent_account_id);
    }
    return false;
  };

  return { flatAccounts, accountTree, loading, error, refetch: fetchAccounts, isDescendant };
}
