import { createContext, useContext, useState, ReactNode, useEffect } from "react";
import { UserProfile, getUserProfile, isProfileComplete as checkProfileComplete, getCachedProfile } from "../../services/profileService";

interface ProfileContextType {
  profile: UserProfile | null;
  isProfileComplete: boolean;
  isLoading: boolean;
  refreshProfile: () => Promise<void>;
}

const ProfileContext = createContext<ProfileContextType | undefined>(undefined);

export function ProfileProvider({ children }: { children: ReactNode }) {
  // استفاده از cached profile به عنوان مقدار اولیه
  const [profile, setProfile] = useState<UserProfile | null>(getCachedProfile());
  const [isLoading, setIsLoading] = useState(true);

  const refreshProfile = async () => {
    setIsLoading(true);
    const userProfile = await getUserProfile();
    setProfile(userProfile);
    setIsLoading(false);
  };

  useEffect(() => {
    refreshProfile();
  }, []);

  const isProfileComplete = checkProfileComplete(profile);

  return (
    <ProfileContext.Provider value={{ profile, isProfileComplete, isLoading, refreshProfile }}>
      {children}
    </ProfileContext.Provider>
  );
}

export function useProfile() {
  const context = useContext(ProfileContext);
  if (!context) {
    throw new Error("useProfile must be used within ProfileProvider");
  }
  return context;
}
