import React, { createContext, useContext, useState, useEffect } from 'react'
import api from '../services/api'
import toast from 'react-hot-toast'

const AuthContext = createContext()

export const useAuth = () => {
  const context = useContext(AuthContext)
  if (!context) {
    throw new Error('useAuth must be used within an AuthProvider')
  }
  return context
}

export const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    // Check for existing token on app start and validate it
    checkAuthStatus()
  }, [])

  const checkAuthStatus = async () => {
    const token = localStorage.getItem('management_token')
    const savedUser = localStorage.getItem('management_user')
    
    if (!token || !savedUser) {
      setLoading(false)
      return
    }
    
    try {
      // Validate token by making a simple API call
      const response = await api.get('/management/tenants?limit=1')
      // If successful, use saved user data
      const parsedUser = JSON.parse(savedUser)
      setUser(parsedUser)
      console.log('✅ Management token validated for user:', parsedUser.username)
    } catch (error) {
      console.warn('🔓 Management token validation failed:', error.response?.status, error.response?.data?.message)
      // Clear invalid auth data (but don't redirect here, let the api interceptor handle it)
      localStorage.removeItem('management_token')
      localStorage.removeItem('management_user')
      setUser(null)
    } finally {
      setLoading(false)
    }
  }

  const login = async (username, password) => {
    try {
      // Use dedicated management auth endpoint
      const response = await api.post('/management/auth/login', {
        username,
        password
      })

      const { token, user: userData } = response.data

      // Verify management user
      if (!userData.role || !['super_admin', 'platform_admin'].includes(userData.role)) {
        throw new Error('Access denied. Management privileges required.')
      }

      localStorage.setItem('management_token', token)
      localStorage.setItem('management_user', JSON.stringify(userData))
      setUser(userData)

      toast.success(`Welcome, ${userData.username}! Management access granted.`)
      return { success: true }
    } catch (error) {
      const message = error.response?.data?.message || error.message || 'Management login failed'
      toast.error(message)
      return { success: false, message }
    }
  }

  const logout = () => {
    localStorage.removeItem('management_token')
    localStorage.removeItem('management_user')
    setUser(null)
    toast.success('Logged out successfully')
  }

  const value = {
    user,
    loading,
    login,
    logout,
    checkAuthStatus,
    isAuthenticated: !!user,
    isAdmin: user?.role === 'admin' || user?.role === 'super_admin' || user?.role === 'platform_admin',
    isSuperAdmin: user?.role === 'super_admin',
    isPlatformAdmin: user?.role === 'platform_admin'
  }

  return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>
}

export default AuthContext
