"use client"

import { useEffect, useState } from "react"
import { useRouter, useSearchParams } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Sparkles, Loader2, ExternalLink } from "lucide-react"

export default function AuthPage() {
  const [isAuthenticating, setIsAuthenticating] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const router = useRouter()
  const searchParams = useSearchParams()

  useEffect(() => {
    // Check if we have auth code in URL
    const code = searchParams.get('code')
    const error = searchParams.get('error')
    const success = searchParams.get('success')

    if (error) {
      setError(`Authentication failed: ${error}`)
      return
    }

    if (success === 'true') {
      // Successfully authenticated, redirect to home
      router.push('/')
      return
    }

    if (code) {
      handleAuthCallback(code)
    }
  }, [searchParams, router])

  const handleAuthCallback = async (authCode: string) => {
    setIsAuthenticating(true)
    setError(null)

    try {
      // Exchange auth code for access token
      const response = await fetch('/api/auth/qwen/callback', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ code: authCode }),
      })

      if (!response.ok) {
        throw new Error('Token exchange failed')
      }

      const data = await response.json()
      
      if (data.success) {
        // Store the token (in production, this would be more secure)
        localStorage.setItem('qwen_access_token', data.access_token)
        localStorage.setItem('qwen_authenticated', 'true')
        
        // Redirect to home
        router.push(data.redirect_to || '/')
      } else {
        throw new Error(data.error || 'Authentication failed')
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Authentication failed')
    } finally {
      setIsAuthenticating(false)
    }
  }

  const handleQwenOAuth = () => {
    // Redirect to Qwen OAuth for actual authentication
    const clientId = process.env.NEXT_PUBLIC_QWEN_CLIENT_ID || 'demo_client_id'
    const redirectUri = encodeURIComponent(process.env.NEXT_PUBLIC_QWEN_REDIRECT_URI || 'http://localhost:3000/auth')
    const scope = 'api_access'
    const state = Math.random().toString(36).substring(7)

    // Store state for CSRF protection
    localStorage.setItem('qwen_auth_state', state)
    
    // Qwen OAuth URL (following Qwen Code implementation)
    const authUrl = `https://qwen.ai/oauth/authorize?client_id=${clientId}&redirect_uri=${redirectUri}&scope=${scope}&response_type=code&state=${state}`
    
    window.location.href = authUrl
  }

  const handleDirectLogin = () => {
    // Direct login for demo - simulates successful OAuth
    const mockToken = `demo_token_${Date.now()}`
    localStorage.setItem('qwen_access_token', mockToken)
    localStorage.setItem('qwen_authenticated', 'true')
    router.push('/')
  }

  if (isAuthenticating) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <Card className="w-96">
          <CardContent className="pt-6">
            <div className="text-center space-y-4">
              <Loader2 className="h-8 w-8 animate-spin mx-auto text-blue-600" />
              <p className="text-gray-600">Authenticating with Qwen...</p>
            </div>
          </CardContent>
        </Card>
      </div>
    )
  }

  return (
    <div className="min-h-screen flex items-center justify-center">
      <Card className="w-96">
        <CardHeader className="text-center">
          <div className="flex justify-center mb-4">
            <Sparkles className="h-12 w-12 bg-gradient-to-r from-blue-600 to-purple-600" />
          </div>
          <CardTitle className="text-2xl">Welcome to NanoJason</CardTitle>
          <CardDescription>
            Connect with Qwen AI to start creating stunning image series
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          {error && (
            <div className="p-3 bg-red-50 border border-red-200 rounded-lg text-red-700 text-sm">
              {error}
            </div>
          )}
          
          <div className="space-y-3">
            <Button 
              onClick={handleDirectLogin} 
              className="w-full bg-blue-600 text-white hover:bg-blue-700"
              size="lg"
            >
              <Sparkles className="mr-2 h-4 w-4" />
              Quick Demo Login
            </Button>
            
            <div className="relative">
              <div className="absolute inset-0 flex items-center">
                <span className="bg-white px-2 text-xs text-gray-500">OR</span>
              </div>
              <hr className="border-gray-300" />
            </div>
            
            <Button 
              onClick={handleQwenOAuth} 
              variant="outline"
              className="w-full"
              size="lg"
            >
              <ExternalLink className="mr-2 h-4 w-4" />
              Connect with Qwen OAuth
            </Button>
          </div>
          
          <div className="text-xs text-gray-600 text-center space-y-1">
            <p>By connecting, you agree to Qwen's terms of service</p>
            <p className="font-medium">🚀 Free tier: 2,000 requests/day</p>
            <p className="text-green-600">⚡ 60 requests/minute limit</p>
            <p className="text-blue-600">🔐 OAuth authentication with automatic token refresh</p>
          </div>
        </CardContent>
      </Card>
    </div>
  )
}