"use client"

import { useState } from "react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"

export default function TestGooglePage() {
  const [status, setStatus] = useState<string>("")
  const [logs, setLogs] = useState<string[]>([])

  const addLog = (message: string) => {
    console.log(message)
    setLogs(prev => [...prev, `${new Date().toLocaleTimeString()}: ${message}`])
  }

  const testGoogleConfig = () => {
    setLogs([])
    addLog("Testing Google OAuth configuration...")
    
    const clientId = process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID
    addLog(`Client ID: ${clientId ? 'Present' : 'Missing'}`)
    
    if (!clientId) {
      setStatus("❌ Google Client ID not configured")
      return
    }
    
    setStatus("✅ Google Client ID configured")
  }

  const testGoogleScript = async () => {
    addLog("Testing Google Identity Services script...")
    
    try {
      // Load Google Identity Services
      const script = document.createElement('script')
      script.src = 'https://accounts.google.com/gsi/client'
      script.async = true
      script.defer = true
      
      script.onload = () => {
        addLog("✅ Google Identity Services script loaded successfully")
        
        if (window.google?.accounts?.id) {
          addLog("✅ Google Identity Services API available")
          setStatus("✅ Google script loaded and API available")
        } else {
          addLog("❌ Google Identity Services API not available")
          setStatus("❌ Google API not available after script load")
        }
      }
      
      script.onerror = () => {
        addLog("❌ Failed to load Google Identity Services script")
        setStatus("❌ Failed to load Google script")
      }
      
      document.head.appendChild(script)
    } catch (error: any) {
      addLog(`❌ Error loading Google script: ${error.message}`)
      setStatus("❌ Error loading Google script")
    }
  }

  const testGoogleAuth = async () => {
    addLog("Testing Google authentication flow...")
    
    const clientId = process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID
    if (!clientId) {
      addLog("❌ No client ID available")
      return
    }

    try {
      if (!window.google?.accounts?.id) {
        addLog("❌ Google Identity Services not loaded")
        return
      }

      window.google.accounts.id.initialize({
        client_id: clientId,
        callback: (response: any) => {
          addLog("✅ Google callback received")
          addLog(`Credential length: ${response.credential?.length || 0}`)
          setStatus("✅ Google authentication flow working")
        }
      } as any)

      addLog("✅ Google OAuth initialized")
      
      ;(window.google.accounts.id.prompt as any)((notification: any) => {
        addLog(`Google prompt notification: ${notification.getMomentType()}`)
        if (notification.isNotDisplayed()) {
          addLog("Google One Tap not displayed - this is normal for testing")
        }
      })

    } catch (error: any) {
      addLog(`❌ Error in Google auth: ${error.message}`)
      setStatus("❌ Google authentication error")
    }
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-white to-blue-50/30 py-12">
      <div className="container mx-auto px-4 max-w-4xl">
        <Card className="shadow-xl border-0">
          <CardHeader className="bg-gradient-to-r from-[#3F5CEA] to-[#5B73F0] text-white rounded-t-lg">
            <CardTitle className="text-2xl font-bold">Google OAuth Test Page</CardTitle>
          </CardHeader>
          <CardContent className="p-8">
            <div className="space-y-6">
              <div>
                <h3 className="text-lg font-semibold mb-4">Test Steps</h3>
                <div className="space-y-3">
                  <Button onClick={testGoogleConfig} className="w-full">
                    1. Test Google Configuration
                  </Button>
                  <Button onClick={testGoogleScript} className="w-full">
                    2. Test Google Script Loading
                  </Button>
                  <Button onClick={testGoogleAuth} className="w-full">
                    3. Test Google Authentication
                  </Button>
                </div>
              </div>

              {status && (
                <div className="p-4 bg-gray-100 rounded-lg">
                  <h4 className="font-semibold mb-2">Status:</h4>
                  <p>{status}</p>
                </div>
              )}

              {logs.length > 0 && (
                <div className="p-4 bg-gray-900 text-green-400 rounded-lg font-mono text-sm">
                  <h4 className="font-semibold mb-2 text-white">Logs:</h4>
                  {logs.map((log, index) => (
                    <div key={index}>{log}</div>
                  ))}
                </div>
              )}

              <div className="p-4 bg-blue-50 rounded-lg">
                <h4 className="font-semibold mb-2">Environment Check:</h4>
                <p>
                  <strong>NEXT_PUBLIC_GOOGLE_CLIENT_ID:</strong>{' '}
                  {process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID ? '✅ Set' : '❌ Not set'}
                </p>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  )
}
