import React, { createContext, useContext, useState, useEffect, useCallback, ReactNode } from 'react';
import { API_URL } from '@/lib/config';

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

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

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

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

  // Wrap setStores to track when stores are actually loaded (memoized to prevent re-renders)
  const setStores = useCallback((newStores: StoreData[]) => {
    setStoresState(newStores);
    setStoresLoaded(true);
  }, []);

  // Fetch stores function - can be called from context or externally
  const fetchStores = async () => {
    try {
      const sessionData = localStorage.getItem('session_data');
      if (!sessionData) {
        // No session - mark as loaded with empty stores
        setStores([]);
        return;
      }

      const session = JSON.parse(sessionData);
      const response = await fetch(`${API_URL}/api/stores`, {
        headers: {
          'Authorization': `Bearer ${session.session.access_token}`,
        }
      });

      if (response.ok) {
        const data = await response.json();
        setStores(data.stores || []);
      } else {
        // Request failed - mark as loaded with empty stores
        setStores([]);
      }
    } catch (error) {
      console.error('Error fetching stores in ShopContext:', error);
      // Error occurred - mark as loaded with empty stores
      setStores([]);
    }
  };

  // Fetch stores on mount
  useEffect(() => {
    fetchStores();
  }, []);

  // Load selected shop from URL param or localStorage when stores are loaded
  useEffect(() => {
    // Don't process until stores are actually loaded
    if (!storesLoaded) {
      return;
    }

    const activeStores = stores.filter(s => s.is_active !== false);

    // First priority: check URL query parameter for shop ID
    const urlParams = new URLSearchParams(window.location.search);
    const urlShopId = urlParams.get('shop');

    if (urlShopId && stores.length > 0) {
      const shopFromUrl = stores.find(s => s.id === urlShopId);
      if (shopFromUrl && shopFromUrl.is_active !== false) {
        setSelectedShopState(shopFromUrl);
        localStorage.setItem('selected_shop_id', urlShopId);
        setIsLoading(false);
        setIsShopSelecting(false);
        return;
      }
    }

    // Second priority: check localStorage
    const savedShopId = localStorage.getItem('selected_shop_id');

    if (savedShopId && stores.length > 0) {
      const shop = stores.find(s => s.id === savedShopId);
      // Only auto-select if the saved shop is active
      if (shop && shop.is_active !== false) {
        setSelectedShopState(shop);
      } else if (activeStores.length > 0) {
        // If saved shop not found or inactive, select first active store
        setSelectedShopState(activeStores[0]);
      } else {
        // No active stores available
        setSelectedShopState(null);
      }
    } else if (activeStores.length > 0 && !selectedShop) {
      // Auto-select first active store if none selected
      setSelectedShopState(activeStores[0]);
    }
    setIsLoading(false);
    setIsShopSelecting(false);
  }, [stores, storesLoaded]);

  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, isShopSelecting, storesLoaded, refreshStores: fetchStores }}>
      {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;
};
