import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { Household, HouseholdItem, ShoppingListEntry } from '../types';
import { subscribeToItems } from '../services/items';
import { subscribeToShoppingList } from '../services/shopping';
import { scheduleExpiryCheck } from '../services/notifications';
import { useEffect } from 'react';

interface HouseholdStore {
  household: Household | null;
  deviceId: string | null;
  items: HouseholdItem[];
  shoppingList: ShoppingListEntry[];
  isInitialized: boolean;
  setHousehold: (h: Household | null) => void;
  setDeviceId: (id: string) => void;
  setItems: (items: HouseholdItem[]) => void;
  setShoppingList: (entries: ShoppingListEntry[]) => void;
  setInitialized: () => void;
}

export const useHouseholdStore = create<HouseholdStore>()(
  persist(
    (set) => ({
      household: null,
      deviceId: null,
      items: [],
      shoppingList: [],
      isInitialized: false,
      setHousehold: (h) => set({ household: h }),
      setDeviceId: (id) => set({ deviceId: id }),
      setItems: (items) => set({ items }),
      setShoppingList: (shoppingList) => set({ shoppingList }),
      setInitialized: () => set({ isInitialized: true }),
    }),
    {
      name: 'houseorg-store',
      storage: createJSONStorage(() => {
        // AsyncStorage uses window.localStorage on web — not available during SSR (Node.js)
        if (typeof window === 'undefined') {
          return { getItem: () => null, setItem: () => {}, removeItem: () => {} };
        }
        return AsyncStorage;
      }),
      partialize: (s) => ({
        household: s.household,
        deviceId: s.deviceId,
        items: s.items,
        shoppingList: s.shoppingList,
        // isInitialized intentionally excluded — runtime-only flag
      }),
    }
  )
);

export function useRealtimeSync() {
  const household = useHouseholdStore((s) => s.household);
  const setItems = useHouseholdStore((s) => s.setItems);
  const setShoppingList = useHouseholdStore((s) => s.setShoppingList);

  useEffect(() => {
    if (!household) return;
    const unsubItems = subscribeToItems(household.id, (items) => {
      setItems(items);
      scheduleExpiryCheck(items).catch(() => {});
    });
    const unsubList = subscribeToShoppingList(household.id, setShoppingList);
    return () => {
      unsubItems();
      unsubList();
    };
  }, [household?.id]);
}
