import { createContext, useContext, useState, useEffect, type ReactNode } from 'react'
import type { User, LoginRequest, RegisterRequest } from '@/types'
import * as authService from '@/services/authService'

interface AuthContextType {
  user: User | null
  isLoading: boolean
  isAdmin: boolean
  login: (data: LoginRequest) => Promise<void>
  register: (data: RegisterRequest) => Promise<void>
  logout: () => Promise<void>
  refreshUser: () => Promise<void>
}

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

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

  useEffect(() => {
    const token = localStorage.getItem('access_token')
    if (token) {
      authService.getMe()
        .then(setUser)
        .catch(() => {
          localStorage.removeItem('access_token')
          localStorage.removeItem('refresh_token')
        })
        .finally(() => setIsLoading(false))
    } else {
      setIsLoading(false)
    }
  }, [])

  const loginFn = async (data: LoginRequest) => {
    const result = await authService.login(data)
    setUser(result.user)
  }

  const registerFn = async (data: RegisterRequest) => {
    await authService.register(data)
  }

  const logoutFn = async () => {
    await authService.logout()
    setUser(null)
  }

  const refreshUserFn = async () => {
    const updatedUser = await authService.getMe()
    setUser(updatedUser)
  }

  return (
    <AuthContext.Provider value={{
      user,
      isLoading,
      isAdmin: user?.role === 'admin',
      login: loginFn,
      register: registerFn,
      logout: logoutFn,
      refreshUser: refreshUserFn,
    }}>
      {children}
    </AuthContext.Provider>
  )
}

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