import { useState, useEffect, useCallback } from 'react';
import { fetchCurrentUserProfile } from '../services/userProfileService';
import { getStoredRoleProfile, getStoredUserEmail } from '../utils/roleAccess';

interface UseRoleProfileResult {
  roleProfile: string;
  userEmail: string;
  loading: boolean;
  refreshRoleProfile: () => Promise<void>;
}

export function useRoleProfile(): UseRoleProfileResult {
  const [roleProfile, setRoleProfile] = useState(getStoredRoleProfile);
  const [userEmail, setUserEmail] = useState(getStoredUserEmail);
  const [loading, setLoading] = useState(!getStoredRoleProfile());

  const refreshRoleProfile = useCallback(async () => {
    const storedUser = localStorage.getItem('user');
    if (!storedUser) {
      setRoleProfile('');
      setUserEmail('');
      setLoading(false);
      return;
    }

    try {
      setLoading(true);
      const profile = await fetchCurrentUserProfile();
      const parsed = JSON.parse(storedUser);
      const updatedUser = {
        ...parsed,
        email: profile.email || profile.name || parsed.email,
        role_profile_name: profile.role_profile_name || '',
        full_name: profile.full_name || parsed.full_name,
        custom_site_name: profile.custom_site_name || '',
        custom_phcc_site_name: profile.custom_phcc_site_name || '',
      };

      localStorage.setItem('user', JSON.stringify(updatedUser));
      setRoleProfile(updatedUser.role_profile_name || '');
      setUserEmail(updatedUser.email || profile.name || '');
    } catch (error) {
      console.error('[useRoleProfile] Failed to load role profile:', error);
      setRoleProfile(getStoredRoleProfile());
      setUserEmail(getStoredUserEmail());
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    if (!getStoredRoleProfile()) {
      refreshRoleProfile();
    } else {
      setRoleProfile(getStoredRoleProfile());
      setUserEmail(getStoredUserEmail());
      setLoading(false);
    }
  }, [refreshRoleProfile]);

  return { roleProfile, userEmail, loading, refreshRoleProfile };
}

export default useRoleProfile;
