import {
  createContext,
  useCallback,
  useContext,
  useEffect,
  useMemo,
  useState,
  type ReactNode,
} from 'react'
import { ApiError, getAccessToken, isAbortError } from '../lib/api'
import { fetchCurrentUser, login as loginRequest, logout as logoutRequest } from '../services/authService'
import type { AuthUser } from '../types/auth'

interface AuthContextValue {
  user: AuthUser | null
  isLoading: boolean
  login: (cellNumber: string, password: string) => Promise<void>
  logout: () => void
  setUser: (user: AuthUser) => void
}

const AuthContext = createContext<AuthContextValue | null>(null)

export function AuthProvider({ children }: { children: ReactNode }) {
  const [user, setUser] = useState<AuthUser | null>(null)
  const [isLoading, setIsLoading] = useState(true)

  const logout = useCallback(() => {
    logoutRequest()
    setUser(null)
  }, [])

  useEffect(() => {
    const controller = new AbortController()

    async function init() {
      if (!getAccessToken()) {
        if (!controller.signal.aborted) setIsLoading(false)
        return
      }

      try {
        const { user: currentUser } = await fetchCurrentUser(controller.signal)
        if (controller.signal.aborted) return
        if (currentUser.dashboard !== 'super_admin') {
          logout()
          return
        }
        setUser(currentUser)
      } catch (err) {
        if (isAbortError(err) || controller.signal.aborted) return
        logout()
      } finally {
        if (!controller.signal.aborted) setIsLoading(false)
      }
    }

    void init()

    return () => {
      controller.abort()
    }
  }, [logout])

  const login = useCallback(
    async (cellNumber: string, password: string) => {
      const data = await loginRequest(cellNumber, password)

      if (data.user.dashboard !== 'super_admin') {
        logoutRequest()
        throw new ApiError(
          'This account does not have super admin access. Use the correct dashboard for your role.',
          403,
        )
      }

      setUser(data.user)
    },
    [],
  )

  const value = useMemo(
    () => ({ user, isLoading, login, logout, setUser }),
    [user, isLoading, login, logout],
  )

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

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