import { useState, useEffect } from 'react';
import { inventoryAPI } from '../utils/api';

export interface InventoryItem {
  id: string;
  name: string;
  description?: string;
  quantity: number;
  unit?: string;
  expiryDate?: string;
  isLowStock: boolean;
  imageUrl?: string;
  categoryId?: string;
  createdAt: string;
}

export const useInventory = () => {
  const [items, setItems] = useState<InventoryItem[]>([]);
  const [categories, setCategories] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchInventory = async () => {
    try {
      setLoading(true);
      setError(null);
      const data = await inventoryAPI.getAll();
      setItems(data.items || []);
      setCategories(data.categories || []);
    } catch (err: any) {
      setError(err.message || 'Failed to fetch inventory');
      setItems([]);
    } finally {
      setLoading(false);
    }
  };

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

  return { items, categories, loading, error, refetch: fetchInventory };
};

