import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';

interface StoreData {
  id: string;
  store_name: string | null;
  platform_name: string;
  store_url: string | null;
}

interface ShopContextType {
  selectedShop: StoreData | null;
  setSelectedShop: (shop: StoreData | null) => void;
  stores: StoreData[];
  setStores: (stores: StoreData[]) => void;
  isLoading: boolean;
}

const ShopContext = createContext<ShopContextType | undefined>(undefined);

export const ShopProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  const [selectedShop, setSelectedShopState] = useState<StoreData | null>(null);
  const [stores, setStores] = useState<StoreData[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  // Load selected shop from localStorage on mount
  useEffect(() => {
    const savedShopId = localStorage.getItem('selected_shop_id');
    if (savedShopId && stores.length > 0) {
      const shop = stores.find(s => s.id === savedShopId);
      if (shop) {
        setSelectedShopState(shop);
      } else if (stores.length > 0) {
        // If saved shop not found, select first available
        setSelectedShopState(stores[0]);
      }
    } else if (stores.length > 0 && !selectedShop) {
      // Auto-select first store if none selected
      setSelectedShopState(stores[0]);
    }
    setIsLoading(false);
  }, [stores]);

  const setSelectedShop = (shop: StoreData | null) => {
    setSelectedShopState(shop);
    if (shop) {
      localStorage.setItem('selected_shop_id', shop.id);
    } else {
      localStorage.removeItem('selected_shop_id');
    }
  };

  return (
    <ShopContext.Provider value={{ selectedShop, setSelectedShop, stores, setStores, isLoading }}>
      {children}
    </ShopContext.Provider>
  );
};

export const useShop = (): ShopContextType => {
  const context = useContext(ShopContext);
  if (context === undefined) {
    throw new Error('useShop must be used within a ShopProvider');
  }
  return context;
};
