import { useState, useEffect, useCallback } from 'react';
import { api } from '@/lib/api';
import type { Account } from '@/types';

export function useAccounts() {
  const [accounts, setAccounts] = useState<Account[]>([]);
  const [loading, setLoading] = useState(true);

  const refresh = useCallback(() => {
    api.listAccounts().then(setAccounts).finally(() => setLoading(false));
  }, []);

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

  const create = (data: Partial<Account>) => api.createAccount(data).then(refresh);
  const update = (id: string, data: Partial<Account>) => api.updateAccount(id, data).then(refresh);
  const remove = (id: string) => api.deleteAccount(id).then(refresh);

  return { accounts, loading, refresh, create, update, remove };
}
