import { createContext, useContext, useEffect, useState } from 'react';
import { getHouseholdStores } from '../api/stores';
import { AuthContext } from './AuthContext';
import { HouseholdContext } from './HouseholdContext';

export const StoreContext = createContext({
  stores: [],
  activeStore: null,
  loading: false,
  error: null,
  setActiveStore: () => { },
  refreshStores: () => { },
});

export const StoreProvider = ({ children }) => {
  const { token } = useContext(AuthContext);
  const { activeHousehold } = useContext(HouseholdContext);
  const [stores, setStores] = useState([]);
  const [activeStore, setActiveStoreState] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  // Load stores when household changes
  useEffect(() => {
    if (token && activeHousehold) {
      loadStores();
    } else {
      // Clear state when logged out or no household
      setStores([]);
      setActiveStoreState(null);
    }
  }, [token, activeHousehold?.id]);

  // Load active store from localStorage on mount (per household)
  useEffect(() => {
    if (!activeHousehold || stores.length === 0) return;

    console.log('[StoreContext] Setting active store from:', stores);
    const storageKey = `activeStoreId_${activeHousehold.id}`;
    const savedStoreId = localStorage.getItem(storageKey);

    if (savedStoreId) {
      const store = stores.find(s => s.id === parseInt(savedStoreId));
      if (store) {
        console.log('[StoreContext] Found saved store:', store);
        setActiveStoreState(store);
        return;
      }
    }

    // No saved store or not found, use default or first one
    const defaultStore = stores.find(s => s.is_default) || stores[0];
    console.log('[StoreContext] Using store:', defaultStore);
    setActiveStoreState(defaultStore);
    localStorage.setItem(storageKey, defaultStore.id);
  }, [stores, activeHousehold]);

  const loadStores = async () => {
    if (!token || !activeHousehold) return;

    setLoading(true);
    setError(null);
    try {
      console.log('[StoreContext] Loading stores for household:', activeHousehold.id);
      const response = await getHouseholdStores(activeHousehold.id);
      console.log('[StoreContext] Loaded stores:', response.data);
      setStores(response.data);
    } catch (err) {
      console.error('[StoreContext] Failed to load stores:', err);
      setError(err.response?.data?.message || 'Failed to load stores');
      setStores([]);
    } finally {
      setLoading(false);
    }
  };

  const setActiveStore = (store) => {
    setActiveStoreState(store);
    if (store && activeHousehold) {
      const storageKey = `activeStoreId_${activeHousehold.id}`;
      localStorage.setItem(storageKey, store.id);
    }
  };

  const value = {
    stores,
    activeStore,
    loading,
    error,
    setActiveStore,
    refreshStores: loadStores,
  };

  return (
    <StoreContext.Provider value={value}>
      {children}
    </StoreContext.Provider>
  );
};
