import { createContext, useContext, useState, useEffect } from 'react'

const AuthContext = createContext(null)

export const AuthProvider = ({ children }) => {
  const [isAuthenticated, setIsAuthenticated] = useState(false)
  const [user, setUser] = useState(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    // Prüfe beim Start, ob bereits ein Login-Token vorhanden ist
    const storedAuth = localStorage.getItem('auth')
    if (storedAuth) {
      try {
        const authData = JSON.parse(storedAuth)
        if (authData.user && authData.credentials) {
          setUser(authData.user)
          setIsAuthenticated(true)
        }
      } catch (err) {
        console.error('Fehler beim Laden der Auth-Daten:', err)
        localStorage.removeItem('auth')
      }
    }
    setLoading(false)
  }, [])

  const login = async (username, password) => {
    try {
      // Erstelle Basic Auth Header
      const credentials = btoa(`${username}:${password}`)
      
      console.log('Sende Login-Request:', { username, hasPassword: !!password })
      
      const response = await fetch('/api/login', {
        method: 'POST',
        headers: {
          'Authorization': `Basic ${credentials}`,
          'Content-Type': 'application/json',
        },
      })

      console.log('Login-Response Status:', response.status)

      if (response.ok) {
        const data = await response.json()
        console.log('Login erfolgreich:', data)
        const authData = {
          user: data.user,
          credentials: credentials
        }
        localStorage.setItem('auth', JSON.stringify(authData))
        setUser(data.user)
        setIsAuthenticated(true)
        return { success: true, user: data.user }
      } else {
        const errorText = await response.text()
        console.error('Login-Fehler Response:', errorText)
        let errorData
        try {
          errorData = JSON.parse(errorText)
        } catch {
          errorData = { error: errorText || 'Ungültige Anmeldedaten' }
        }
        return { success: false, error: errorData.error || 'Ungültige Anmeldedaten' }
      }
    } catch (err) {
      console.error('Login-Fehler (Exception):', err)
      return { success: false, error: 'Fehler bei der Anmeldung: ' + err.message }
    }
  }

  const logout = () => {
    localStorage.removeItem('auth')
    setUser(null)
    setIsAuthenticated(false)
  }

  const getAuthHeader = () => {
    const storedAuth = localStorage.getItem('auth')
    if (storedAuth) {
      try {
        const authData = JSON.parse(storedAuth)
        if (authData.credentials) {
          return `Basic ${authData.credentials}`
        }
      } catch (err) {
        console.error('Fehler beim Laden der Auth-Daten:', err)
      }
    }
    return null
  }

  // Authenticated fetch wrapper
  const authFetch = async (url, options = {}) => {
    const authHeader = getAuthHeader()
    
    // Wenn Content-Type bereits gesetzt ist (z.B. für multipart/form-data), nicht überschreiben
    const defaultHeaders = {}
    // Nur Content-Type setzen, wenn es nicht FormData ist (FormData setzt Content-Type automatisch)
    if (!(options.body instanceof FormData)) {
      if (!options.headers || !options.headers['Content-Type']) {
        defaultHeaders['Content-Type'] = 'application/json'
      }
    }
    if (!options.headers || !options.headers['Accept']) {
      defaultHeaders['Accept'] = 'application/json'
    }
    
    const headers = {
      ...defaultHeaders,
      ...options.headers,
      ...(authHeader && { 'Authorization': authHeader }),
    }

    const response = await fetch(url, {
      ...options,
      headers,
    })

    // Wenn 401 Unauthorized, logout
    if (response.status === 401) {
      logout()
      window.location.href = '/login'
    }

    return response
  }

  const value = {
    isAuthenticated,
    user,
    loading,
    login,
    logout,
    getAuthHeader,
    authFetch,
  }

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

export const useAuth = () => {
  const context = useContext(AuthContext)
  if (!context) {
    throw new Error('useAuth muss innerhalb eines AuthProvider verwendet werden')
  }
  return context
}

