import { createContext, useContext, useState, useEffect } from 'react'
import { useAuth } from './AuthContext'
import { getCurrentProfile, listProfiles } from '../utils/api'

const ProfileContext = createContext(null)

export function ProfileProvider({ children }) {
  const { user, isAuthenticated } = useAuth()
  const [profiles, setProfiles] = useState([])
  const [activeProfile, setActiveProfileState] = useState(null)
  const [loading, setLoading] = useState(true)

  const loadProfiles = async (authUser) => {
    try {
      if (!authUser?.id) return []
      const admin = authUser.role === 'admin' || authUser.role === 'superadmin'
      if (admin) {
        try {
          return await listProfiles()
        } catch {
          const me = await getCurrentProfile()
          return me ? [me] : []
        }
      }
      const me = await getCurrentProfile()
      return me ? [me] : []
    } catch {
      return []
    }
  }

  useEffect(() => {
    if (!isAuthenticated || !user?.id) {
      setActiveProfileState(null)
      setProfiles([])
      setLoading(false)
      return
    }
    setLoading(true)
    loadProfiles(user).then((data) => {
      const rows = Array.isArray(data) ? data : []
      setProfiles(rows)
      const uid = user.id
      const match = rows.find((p) => String(p.id) === String(uid))
      setActiveProfileState(match || rows[0] || null)
      setLoading(false)
    })
  }, [isAuthenticated, user?.id, user?.role])

  const setActiveProfile = (profile) => {
    setActiveProfileState(profile)
    localStorage.setItem('shinkan_active_profile', String(profile.id))
  }

  const refreshProfiles = () =>
    loadProfiles(user).then((data) => {
      setProfiles(Array.isArray(data) ? data : [])
      if (activeProfile) {
        const updated = data.find((p) => String(p.id) === String(activeProfile.id))
        if (updated) setActiveProfileState(updated)
      }
    })

  return (
    <ProfileContext.Provider
      value={{ profiles, activeProfile, setActiveProfile, refreshProfiles, loading }}
    >
      {children}
    </ProfileContext.Provider>
  )
}

export function useProfile() {
  return useContext(ProfileContext)
}
