import React, { createContext, useContext, useState, useEffect } from "react";
import { useAuth } from "./AuthContext";

const REGION_KEY = "photum_selected_region";

interface RegionContextType {
  currentRegion: string;
  setRegion: (region: string) => void;
  availableRegions: string[];
  isRegionReady: boolean;
}

const RegionContext = createContext<RegionContextType>({
  currentRegion: "SP",
  setRegion: () => {},
  availableRegions: [],
  isRegionReady: false,
});

export const RegionProvider: React.FC<{ children: React.ReactNode }> = ({
  children,
}) => {
  const { user } = useAuth();
  
  const [currentRegion, setCurrentRegion] = useState(() => {
    return localStorage.getItem(REGION_KEY) || "SP";
  });

  // Calculate available regions based on user permissions
  // If user is null (public), default to SP or both? 
  // Requirement: Public pages might need both for registration? 
  // Actually, RegionSwitcher is usually for logged in header.
  // Registration page has its own selector. 
  // Let's assume public = SP only or no switcher.
  // BUT: If user is logged out, they shouldn't see switcher anyway.
  const [availableRegions, setAvailableRegions] = useState<string[]>(["SP"]);
  const [isRegionReady, setIsRegionReady] = useState(false);

  useEffect(() => {
    console.log("RegionContext Debug:", { user, allowedRegions: user?.allowedRegions });
    // If not logged in or user still fetching, wait (but if public page, we could mark ready. For now, mark ready if no token or after user loads)
    const token = localStorage.getItem("token");
    if (token && !user) {
       // Wait for user to load to evaluate regions
       setIsRegionReady(false);
       return;
    }

    if (user && user.allowedRegions && user.allowedRegions.length > 0) {
      setAvailableRegions(user.allowedRegions);
      
      // If current region is not in allowed list, switch to first allowed
      if (!user.allowedRegions.includes(currentRegion)) {
        console.log("Switching region to allowed:", user.allowedRegions[0]);
        const fallback = user.allowedRegions[0];
        setCurrentRegion(fallback);
        localStorage.setItem(REGION_KEY, fallback);
      }
    } else {
        // Fallback or Public
        setAvailableRegions(["SP"]);
    }
    
    setIsRegionReady(true);
  }, [user, currentRegion]);

  useEffect(() => {
    localStorage.setItem(REGION_KEY, currentRegion);
  }, [currentRegion]);

  const setRegion = (region: string) => {
    // Prevent switching if not allowed
    if (!availableRegions.includes(region)) return;
    
    setCurrentRegion(region);
    setTimeout(() => {
        window.location.reload();
    }, 100);
  };

  return (
    <RegionContext.Provider
      value={{ currentRegion, setRegion, availableRegions, isRegionReady }}
    >
      {children}
    </RegionContext.Provider>
  );
};

export const useRegion = () => useContext(RegionContext);
