'use client'

import { useState } from 'react'

export default function DebugPage() {
  const [input, setInput] = useState('She felt ashamed of her mistake and apologized.')
  const [response, setResponse] = useState('')
  const [loading, setLoading] = useState(false)

  const testDirectApi = async () => {
    setLoading(true)
    setResponse('測試中...')

    try {
      console.log('=== 開始API測試 ===')
      console.log('輸入:', input)

      const apiResponse = await fetch('http://localhost:5000/api/ai/analyze-sentence', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          inputText: input,
          forceRefresh: true
        })
      })

      console.log('API狀態:', apiResponse.status)

      if (!apiResponse.ok) {
        throw new Error(`API錯誤: ${apiResponse.status}`)
      }

      const data = await apiResponse.json()
      console.log('API回應:', data)

      // 直接顯示結果，不經過複雜的狀態管理
      const translation = data.data?.sentenceMeaning?.translation || '無翻譯'
      const explanation = data.data?.sentenceMeaning?.explanation || '無解釋'
      const highValueWords = data.data?.highValueWords || []

      setResponse(`
✅ API調用成功

📖 翻譯: ${translation}

📝 解釋: ${explanation}

⭐ 高價值詞彙: ${JSON.stringify(highValueWords)}

🔍 完整響應: ${JSON.stringify(data, null, 2)}
      `)
    } catch (error) {
      console.error('API錯誤:', error)
      setResponse(`❌ 錯誤: ${error}`)
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="p-8 max-w-4xl mx-auto">
      <h1 className="text-2xl font-bold mb-6">🐛 API 調試頁面</h1>

      <div className="space-y-4">
        <div>
          <label className="block text-sm font-medium mb-2">測試句子：</label>
          <input
            type="text"
            value={input}
            onChange={(e) => setInput(e.target.value)}
            className="w-full p-3 border border-gray-300 rounded-lg"
          />
        </div>

        <button
          onClick={testDirectApi}
          disabled={loading}
          className="bg-blue-600 text-white px-6 py-3 rounded-lg hover:bg-blue-700 disabled:opacity-50"
        >
          {loading ? '測試中...' : '🔍 直接測試 API'}
        </button>

        <div className="bg-gray-100 p-4 rounded-lg">
          <h3 className="font-bold mb-2">測試結果：</h3>
          <pre className="text-sm whitespace-pre-wrap">{response || '點擊按鈕開始測試'}</pre>
        </div>

        <div className="bg-yellow-100 p-4 rounded-lg">
          <h3 className="font-bold mb-2">💡 測試說明：</h3>
          <p className="text-sm">
            這個頁面直接調用API，不經過複雜的狀態管理邏輯。
            如果這裡能正常顯示結果，說明問題出在其他頁面的前端邏輯。
          </p>
        </div>
      </div>
    </div>
  )
}