'use client'

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

export default function TestAPIPage() {
  const [competitionId, setCompetitionId] = useState('be47d842-91f1-11f0-8595-bd825523ae01')
  const [results, setResults] = useState<any>({})

  const testAPI = async (endpoint: string, name: string) => {
    try {
      const response = await fetch(`/api/competitions/${competitionId}/${endpoint}`)
      const data = await response.json()
      setResults(prev => ({ ...prev, [name]: data }))
      console.log(`${name} API回應:`, data)
    } catch (error) {
      console.error(`${name} API錯誤:`, error)
      setResults(prev => ({ ...prev, [name]: { error: error.message } }))
    }
  }

  const testAllAPIs = async () => {
    setResults({})
    await Promise.all([
      testAPI('judges', '評審'),
      testAPI('apps', '應用'),
      testAPI('teams', '團隊')
    ])
  }

  return (
    <div className="container mx-auto p-6 space-y-6">
      <Card>
        <CardHeader>
          <CardTitle>API 測試頁面</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div>
            <label className="block text-sm font-medium mb-2">競賽ID:</label>
            <input
              type="text"
              value={competitionId}
              onChange={(e) => setCompetitionId(e.target.value)}
              className="w-full p-2 border rounded"
            />
          </div>
          
          <div className="flex space-x-2">
            <Button onClick={testAllAPIs}>測試所有API</Button>
            <Button onClick={() => testAPI('judges', '評審')}>測試評審API</Button>
            <Button onClick={() => testAPI('apps', '應用')}>測試應用API</Button>
            <Button onClick={() => testAPI('teams', '團隊')}>測試團隊API</Button>
          </div>
        </CardContent>
      </Card>

      {Object.entries(results).map(([name, data]) => (
        <Card key={name}>
          <CardHeader>
            <CardTitle>{name} API 結果</CardTitle>
          </CardHeader>
          <CardContent>
            <pre className="bg-gray-100 p-4 rounded overflow-auto text-sm">
              {JSON.stringify(data, null, 2)}
            </pre>
          </CardContent>
        </Card>
      ))}
    </div>
  )
}
