import React, { createContext, useContext, useEffect, useState } from 'react'
import * as SecureStore from 'expo-secure-store'

interface User {
  id: string
  email: string
  firstName: string
  lastName: string
  role: string
  phone?: string
}

interface AuthContextType {
  user: User | null
  login: (user: User) => Promise<void>
  logout: () => Promise<void>
  isLoading: boolean
}

const AuthContext = createContext<AuthContextType | undefined>(undefined)

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

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

  const loadUser = async () => {
    try {
      const userData = await SecureStore.getItemAsync('user')
      if (userData) {
        setUser(JSON.parse(userData))
      }
    } catch (error) {
      console.error('Failed to load user:', error)
    } finally {
      setIsLoading(false)
    }
  }

  const login = async (userData: User) => {
    try {
      await SecureStore.setItemAsync('user', JSON.stringify(userData))
      setUser(userData)
    } catch (error) {
      console.error('Failed to save user:', error)
      throw error
    }
  }

  const logout = async () => {
    try {
      await SecureStore.deleteItemAsync('user')
      setUser(null)
    } catch (error) {
      console.error('Failed to logout:', error)
      throw error
    }
  }

  return (
    <AuthContext.Provider value={{ user, login, logout, isLoading }}>
      {children}
    </AuthContext.Provider>
  )
}

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