import { createContext, useContext, useState, useEffect, ReactNode } from 'react'
import { authApi, TokenResponse } from '../api/auth'

interface AuthState {
  isAuthenticated: boolean
  username: string | null
  isLoading: boolean
  passwordChangeRequired: boolean
  isAdmin: boolean
}

interface AuthContextType extends AuthState {
  login: (username: string, password: string) => Promise<{ success: boolean; error?: string; passwordChangeRequired?: boolean }>
  logout: () => void
  clearPasswordChangeRequired: () => void
}

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

export function AuthProvider({ children }: { children: ReactNode }) {
  const [authState, setAuthState] = useState<AuthState>({
    isAuthenticated: false,
    username: null,
    isLoading: true,
    passwordChangeRequired: false,
    isAdmin: false,
  })

  useEffect(() => {
    const token = localStorage.getItem('access_token')
    if (token) {
      authApi
        .me()
        .then((user) => {
          setAuthState({
            isAuthenticated: true,
            username: user.username,
            isLoading: false,
            passwordChangeRequired: false,
            isAdmin: user.is_admin || false,
          })
        })
        .catch(() => {
          localStorage.removeItem('access_token')
          localStorage.removeItem('refresh_token')
          setAuthState({
            isAuthenticated: false,
            username: null,
            isLoading: false,
            passwordChangeRequired: false,
            isAdmin: false,
          })
        })
    } else {
      setAuthState({
        isAuthenticated: false,
        username: null,
        isLoading: false,
        passwordChangeRequired: false,
        isAdmin: false,
      })
    }
  }, [])

  const login = async (username: string, password: string) => {
    try {
      const tokens: TokenResponse = await authApi.login({ username, password })
      localStorage.setItem('access_token', tokens.access_token)
      localStorage.setItem('refresh_token', tokens.refresh_token)
      const user = await authApi.me()
      const passwordChangeRequired = tokens.password_change_required || false
      setAuthState({
        isAuthenticated: true,
        username: user.username,
        isLoading: false,
        passwordChangeRequired,
        isAdmin: user.is_admin || false,
      })
      return { success: true, passwordChangeRequired }
    } catch (error: any) {
      return {
        success: false,
        error: error.response?.data?.detail || 'Login failed',
      }
    }
  }

  const clearPasswordChangeRequired = () => {
    setAuthState((prev) => ({
      ...prev,
      passwordChangeRequired: false,
    }))
  }

  const logout = () => {
    localStorage.removeItem('access_token')
    localStorage.removeItem('refresh_token')
    // Clear sessionStorage settings on logout
    sessionStorage.removeItem('identify_settings')
    setAuthState({
      isAuthenticated: false,
      username: null,
      isLoading: false,
    })
  }

  return (
    <AuthContext.Provider value={{ ...authState, login, logout, clearPasswordChangeRequired }}>
      {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
}

