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[];
}

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

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"]);

  useEffect(() => {
    console.log("RegionContext Debug:", { user, allowedRegions: user?.allowedRegions });
    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"]);
    }
  }, [user, user?.allowedRegions, 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 }}
    >
      {children}
    </RegionContext.Provider>
  );
};

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