import { useEffect } from 'react';
import { Platform } from 'react-native';
import NetInfo from '@react-native-community/netinfo';
import { syncQueue, PendingOp } from '../lib/syncQueue';
import { createItem, updateItem, deleteItem, updateItemQuantity } from '../services/items';
import {
  addToShoppingList,
  checkOffItem,
  removeShoppingEntry,
  clearCheckedItems,
} from '../services/shopping';

async function executeOp(op: PendingOp): Promise<void> {
  const p = op.payload as any;
  switch (op.type) {
    case 'createItem':
      await createItem(p.householdId, p.input);
      break;
    case 'updateItem':
      await updateItem(p.householdId, p.itemId, p.changes);
      break;
    case 'deleteItem':
      await deleteItem(p.householdId, p.itemId);
      break;
    case 'updateItemQuantity':
      await updateItemQuantity(p.householdId, p.itemId, p.qty);
      break;
    case 'addToShoppingList':
      await addToShoppingList(p.householdId, p.entry);
      break;
    case 'checkOffItem':
      await checkOffItem(p.householdId, p.entryId, p.deviceId, p.quantityBought);
      break;
    case 'removeShoppingEntry':
      await removeShoppingEntry(p.householdId, p.entryId);
      break;
    case 'clearCheckedItems':
      await clearCheckedItems(p.householdId);
      break;
  }
}

async function replayQueue(): Promise<void> {
  const ops = await syncQueue.getAll();
  for (const op of ops) {
    try {
      await executeOp(op);
      await syncQueue.remove(op.id);
    } catch {
      break; // stop until next reconnect
    }
  }
}

export function useNetworkSync() {
  useEffect(() => {
    if (Platform.OS === 'web') {
      window.addEventListener('online', replayQueue);
      return () => window.removeEventListener('online', replayQueue);
    }
    const unsubscribe = NetInfo.addEventListener((state) => {
      if (state.isConnected) replayQueue();
    });
    return unsubscribe;
  }, []);
}
