"use client";
import React, { createContext, useContext, useEffect, useState } from "react";
import { getUser, getAllRole } from "@/services/userService";

// Create context
const ProfileContext = createContext();

// Hook for consuming
export const useProfile = () => useContext(ProfileContext);

export default function ProfileProvider({ children }) {
  const [profile, setProfile] = useState(null);
  const [roles, setRoles] = useState([]);
  const [loading, setLoading] = useState(true);

  // Load roles from API
  const loadRoles = async () => {
    try {
      const res = await getAllRole();
      setRoles(res.data);
    } catch (err) {
      console.error("Failed to load roles:", err);
    }
  };

  // Load logged-in user and merge role names
  const loadProfile = async () => {
    try {
      const saved = localStorage.getItem("user");
      if (!saved) {
        setProfile(null);
        setLoading(false);
        return;
      }

      const parsed = JSON.parse(saved);

      const response = await getUser(parsed.id);
      const user = response.data;

      // Convert role IDs → role names
      const userRoleNames = user.roles
        .map((rid) => roles.find((r) => r.id === rid)?.name)
        .filter(Boolean);

      setProfile({
        ...user,
        role_names: userRoleNames,
      });
    } catch (err) {
      console.error("Failed to load profile:", err);
      setProfile(null);
    } finally {
      setLoading(false);
    }
  };

  // Refresh profile after update
  const refreshProfile = async () => {
    setLoading(true);
    await loadProfile();
  };

  useEffect(() => {
    (async () => {
      await loadRoles();
    })();
  }, []);

  useEffect(() => {
    if (roles.length > 0) {
      loadProfile();
    }
  }, [roles]);

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