"use client"

import { useState, useEffect, createContext, useContext, ReactNode } from 'react'
import { useRouter } from 'next/navigation'
import { createAuthHeader } from '@/utils/api-utils'

interface QwenAuthContextType {
  isAuthenticated: boolean
  isLoading: boolean
  login: () => void
  logout: () => void
  accessToken: string | null
  error: string | null
  clearError: () => void
}

const QwenAuthContext = createContext<QwenAuthContextType | undefined>(undefined)

interface QwenAuthProviderProps {
  children: ReactNode
}

export function QwenAuthProvider({ children }: QwenAuthProviderProps) {
  const [isAuthenticated, setIsAuthenticated] = useState(false)
  const [isLoading, setIsLoading] = useState(true)
  const [accessToken, setAccessToken] = useState<string | null>(null)
  const [error, setError] = useState<string | null>(null)
  const router = useRouter()

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

  const checkAuthStatus = async () => {
    setIsLoading(true)
    
    try {
      const token = localStorage.getItem('qwen_access_token')
      
      if (token) {
        // Verify the token is still valid
        const response = await fetch('/api/auth/verify', {
          headers: {
            'Authorization': createAuthHeader(token),
          },
        })

        if (response.ok) {
          setIsAuthenticated(true)
          setAccessToken(token)
        } else {
          // Token is invalid, remove it
          localStorage.removeItem('qwen_access_token')
          setAccessToken(null)
          setIsAuthenticated(false)
        }
      } else {
        setIsAuthenticated(false)
      }
    } catch (err) {
      console.error('Auth check failed:', err)
      setIsAuthenticated(false)
      setAccessToken(null)
      localStorage.removeItem('qwen_access_token')
    } finally {
      setIsLoading(false)
    }
  }

  const login = () => {
    const clientId = process.env.NEXT_PUBLIC_QWEN_CLIENT_ID
    const redirectUri = encodeURIComponent(process.env.NEXT_PUBLIC_QWEN_REDIRECT_URI || `${window.location.origin}/auth`)
    const scope = 'image_generation chat'
    const state = Math.random().toString(36).substring(7)

    localStorage.setItem('qwen_auth_state', state)
    
    const authUrl = `https://open.bigmodel.cn/oauth2/authorize?client_id=${clientId}&redirect_uri=${redirectUri}&scope=${scope}&response_type=code&state=${state}`
    
    window.location.href = authUrl
  }

  const logout = () => {
    localStorage.removeItem('qwen_access_token')
    localStorage.removeItem('qwen_auth_state')
    setIsAuthenticated(false)
    setAccessToken(null)
    setError(null)
    router.push('/')
  }

  const clearError = () => {
    setError(null)
  }

  const value: QwenAuthContextType = {
    isAuthenticated,
    isLoading,
    login,
    logout,
    accessToken,
    error,
    clearError,
  }

  return (
    <QwenAuthContext.Provider value={value}>
      {children}
    </QwenAuthContext.Provider>
  )
}

export function useQwenAuth() {
  const context = useContext(QwenAuthContext)
  
  if (context === undefined) {
    throw new Error('useQwenAuth must be used within a QwenAuthProvider')
  }
  
  return context
}