import { createContext, useState, useEffect, useContext } from 'react'
import { api } from '../utils/api'

const AuthContext = createContext(null)

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

  useEffect(() => {
    checkAuth()
  }, [])

  const checkAuth = async () => {
    try {
      const userData = await api.get('/auth/me')
      setUser(userData)
      const perms = await api.get('/auth/permissions')
      setPermissions(perms)
    } catch (err) {
      console.log('Not authenticated')
      setUser(null)
      setPermissions(null)
    } finally {
      setLoading(false)
    }
  }

  const login = async (email, password) => {
    const response = await api.post('/auth/login', { email, password })
    setUser(response.user)
    // Load permissions after login
    try {
      const perms = await api.get('/auth/permissions')
      setPermissions(perms)
    } catch (err) {
      console.error('Failed to load permissions:', err)
    }
    return response
  }

  const logout = async () => {
    try {
      await api.post('/auth/logout')
    } catch (err) {
      console.error('Logout error:', err)
    } finally {
      setUser(null)
      setPermissions(null)
      window.location.href = '/login'
    }
  }

  // Check if current user owns a resource
  const isOwner = (resource) => {
    if (!user || !resource) return false
    const creatorId = resource.created_by_user_id || resource.createdByUserId
    return creatorId === user.id
  }

  // Check if current user is assigned to a resource
  const isAssignedTo = (resource) => {
    if (!user || !resource) return false
    const assignedTo = resource.assigned_to || resource.assignedTo
    return assignedTo === user.id
  }

  // Check if user can edit a specific resource (owns it, assigned to it, or has role)
  const canEditResource = (type, resource) => {
    if (!permissions) return false
    if (type === 'post') return permissions.canEditAnyPost || isOwner(resource) || isAssignedTo(resource)
    if (type === 'task') return permissions.canEditAnyTask || isOwner(resource) || isAssignedTo(resource)
    if (type === 'campaign') return permissions.canEditCampaigns || isOwner(resource)
    if (type === 'project') return permissions.canEditProjects || isOwner(resource)
    if (type === 'artefact') return permissions.canEditAnyPost || isOwner(resource)
    return false
  }

  const ALL_MODULES = ['marketing', 'projects', 'finance', 'issues']

  const hasModule = (mod) => {
    if (!user) return false
    if (user.role === 'superadmin') return true
    const userModules = Array.isArray(user.modules) ? user.modules : ALL_MODULES
    return userModules.includes(mod)
  }

  const canDeleteResource = (type, resource) => {
    if (!permissions) return false
    if (type === 'post') return permissions.canDeleteAnyPost || isOwner(resource) || isAssignedTo(resource)
    if (type === 'task') return permissions.canDeleteAnyTask || isOwner(resource) || isAssignedTo(resource)
    if (type === 'campaign') return permissions.canDeleteCampaigns || isOwner(resource)
    if (type === 'project') return permissions.canDeleteProjects || isOwner(resource)
    if (type === 'artefact') return permissions.canDeleteAnyPost || isOwner(resource)
    return false
  }

  return (
    <AuthContext.Provider value={{
      user, loading, permissions,
      login, logout, checkAuth,
      isOwner, canEditResource, canDeleteResource,
      hasModule,
    }}>
      {children}
    </AuthContext.Provider>
  )
}

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

export default AuthContext
