import Link from 'next/link'
import { headers } from 'next/headers'

async function fetchReports(baseUrl: string) {
  const url = `${baseUrl}/api/reports?limit=50`
  const resp = await fetch(url, { cache: 'no-store' })
  if (!resp.ok) {
    return { items: [], total: 0 }
  }
  return resp.json() as Promise<{ items: Array<{ id: string; symbol: string; createdAt: string; content?: any }>; total: number }>
}

export default async function ReportsPage() {
  const h = await headers()
  const host = h.get('x-forwarded-host') || h.get('host') || 'localhost:3000'
  const proto = h.get('x-forwarded-proto') || 'http'
  const base = process.env.FRONTEND_INTERNAL_URL || process.env.NEXT_PUBLIC_BASE_URL || `${proto}://${host}`
  const { items, total } = await fetchReports(base)

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-semibold">历史分析报告</h1>
        <div className="text-sm text-muted-foreground">共 {total} 条</div>
      </div>

      {items.length === 0 ? (
        <p className="text-sm text-muted-foreground">暂无报告</p>
      ) : (
        <div className="overflow-x-auto border rounded-md">
          <table className="min-w-full text-sm">
            <thead>
              <tr className="bg-muted">
                <th className="text-left p-3">股票代码</th>
                <th className="text-left p-3">公司名称</th>
                <th className="text-left p-3">创建时间</th>
                <th className="text-right p-3">操作</th>
              </tr>
            </thead>
            <tbody>
              {items.map((r) => {
                const name = (r as any)?.content?.financials?.name || (r as any)?.content?.company_name || ''
                return (
                  <tr key={r.id} className="border-t hover:bg-muted/50">
                    <td className="p-3 font-medium">{r.symbol}</td>
                    <td className="p-3">{name || <span className="text-muted-foreground">-</span>}</td>
                    <td className="p-3">{new Date(r.createdAt).toLocaleString()}</td>
                    <td className="p-3 text-right">
                      <Link href={`/reports/${r.id}`} className="text-primary hover:underline">查看</Link>
                    </td>
                  </tr>
                )
              })}
            </tbody>
          </table>
        </div>
      )}
    </div>
  )
}