'use client'

import { useState, useEffect } from 'react'
import { ollamaClient } from '@/services/ollama-client'

export default function TestErrorPage() {
  const [testResult, setTestResult] = useState<string>('Click test button to start')
  const [error, setError] = useState<string>('')

  const testOllamaConnection = async () => {
    try {
      setTestResult('Testing API key...')
      setError('')
      
      // Test with your actual API key
      const testKey = '81be8de35b254163a87ba41a5e4e565d.x-TOGbA79gS7AAHTwziOUAIb'
      
      console.log('🔍 Testing API key:', testKey)
      console.log('🔍 API key length:', testKey.length)
      console.log('🔍 API key chars:', testKey.split('').map(c => c.charCodeAt(0)))
      
      // Set the API key
      ollamaClient.setApiKey(testKey, false)
      
      // Test if available
      const isAvailable = ollamaClient.isAvailable()
      console.log('🔍 Client available:', isAvailable)
      
      setTestResult(`API Key Set: ${isAvailable ? '✅' : '❌'}`)
      
      if (isAvailable) {
        setTestResult('Testing API call...')
        
        // Try to list models
        const models = await ollamaClient.listModels()
        console.log('✅ Models retrieved:', models)
        setTestResult(`✅ Success! Found ${models.length} models`)
      }
    } catch (err) {
      console.error('❌ Test failed:', err)
      setError(`Error: ${err.message}`)
      setTestResult('❌ Test Failed')
    }
  }

  return (
    <div className="min-h-screen bg-gray-50 p-8">
      <div className="max-w-2xl mx-auto">
        <h1 className="text-3xl font-bold mb-6">API Error Debug Test</h1>
        
        <div className="bg-white rounded-lg shadow p-6 mb-6">
          <h2 className="text-xl font-semibold mb-4">Test Ollama Connection</h2>
          
          <button
            onClick={testOllamaConnection}
            className="bg-blue-500 text-white px-6 py-2 rounded hover:bg-blue-600"
          >
            Test API Connection
          </button>
          
          <div className="mt-4">
            <div className="font-semibold">Test Result:</div>
            <div className="mt-2 p-3 bg-gray-100 rounded">
              {testResult}
            </div>
          </div>
          
          {error && (
            <div className="mt-4">
              <div className="font-semibold text-red-600">Error:</div>
              <div className="mt-2 p-3 bg-red-100 rounded text-red-700">
                {error}
              </div>
            </div>
          )}
        </div>
        
        <div className="bg-white rounded-lg shadow p-6">
          <h2 className="text-xl font-semibold mb-4">Browser Console</h2>
          <p className="text-sm text-gray-600">
            Check the browser console (F12) for detailed debugging information.
          </p>
          <p className="text-sm text-gray-600 mt-2">
            Look for 🔍 emoji markers in console logs.
          </p>
        </div>
      </div>
    </div>
  )
}