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

// Data comes from GET /pantry/pickups — orders reshaped as "pickups" for the staff UI.
interface Pickup {
  id: string;
  name: string;
  quantity: number;
  status: 'pending' | 'ready' | 'picked-up';
  pickupTime: string;
  notes?: string;
  createdAt: string;
  updatedAt: string;
  userId: string;
  userEmail?: string;
  userFullName?: string;
}

export const usePickups = () => {
  const [pickups, setPickups] = useState<Pickup[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchPickups = async () => {
    try {
      setLoading(true);
      setError(null);
      const response = await pickupAPI.getAll();
      setPickups(response.pickups || []);
    } catch (err: any) {
      setError(err.message || 'Failed to fetch pickups');
      console.error('Error fetching pickups:', err);
      // Set empty array on error to prevent breaking the UI
      setPickups([]);
    } finally {
      setLoading(false);
    }
  };

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

  return {
    pickups,
    loading,
    error,
    refetch: fetchPickups
  };
};
