import { useState } from 'react';
import { downloadGuests } from '../services/api';
import { useEventStore } from '../store/eventStore';
import { useUIStore } from '../store/uiStore';

export function useRefreshGuests() {
  const [refreshing, setRefreshing] = useState(false);
  const { setGuests, markLoaded } = useEventStore();
  const showToast = useUIStore(s => s.showToast);

  const refresh = async (onDone?: () => void) => {
    if (refreshing) return;
    setRefreshing(true);
    try {
      const { guests, total } = await downloadGuests();
      setGuests(guests);
      markLoaded(total);
      showToast('success', `${total} guests refreshed.`);
      onDone?.();
    } catch {
      showToast('error', 'Refresh failed. Check your connection.');
    } finally {
      setRefreshing(false);
    }
  };

  return { refresh, refreshing };
}
