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

export interface Order {
  id: string;
  userId: string;
  name: string;
  quantity: number;
  unit: string; // This stores the status
  isPurchased: boolean;
  priority: string; // Pickup time
  notes?: string;
  createdAt: string;
  updatedAt: string;
  user?: {
    id: string;
    fullName?: string;
    email: string;
  };
}

export const useOrders = () => {
  const [orders, setOrders] = useState<Order[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchOrders = async () => {
    try {
      setLoading(true);
      setError(null);
      const data = await ordersAPI.getAll();
      setOrders(data.orders || []);
    } catch (err: any) {
      setError(err.message || 'Failed to fetch orders');
      setOrders([]);
    } finally {
      setLoading(false);
    }
  };

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

  return { orders, loading, error, refetch: fetchOrders };
};

