import { useState, useEffect } from 'react';
import { getCategories, isLoggedIn } from '../lib/api';
import { DEFAULT_CATEGORIES } from '../lib/categories';

export function useCategories() {
  const [categories, setCategories] = useState(DEFAULT_CATEGORIES);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!isLoggedIn()) {
      setLoading(false);
      return;
    }

    const loadCategories = async () => {
      try {
        const categoriesData = await getCategories();
        if (categoriesData) {
          setCategories({
            expense: [
              ...DEFAULT_CATEGORIES.expense,
              ...(categoriesData.expense || []).filter(
                c => !DEFAULT_CATEGORIES.expense.some(d => d.name === c.name)
              )
            ],
            income: [
              ...DEFAULT_CATEGORIES.income,
              ...(categoriesData.income || []).filter(
                c => !DEFAULT_CATEGORIES.income.some(d => d.name === c.name)
              )
            ],
          });
        }
      } catch (err) {
        console.error(err);
      } finally {
        setLoading(false);
      }
    };

    loadCategories();
  }, []);

  return { categories, loading };
}
