"use client"

import { useEffect, useState } from "react"
import Link from "next/link"
import { getReports } from "@/lib/api"
import { Badge } from "@/components/ui/badge"
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card"
import { Loader2 } from "lucide-react"

export function HistoryList() {
    const [reports, setReports] = useState<any[]>([])
    const [loading, setLoading] = useState(true)

    useEffect(() => {
        getReports().then(setReports).catch(console.error).finally(() => setLoading(false))
    }, [])

    if (loading) return <Loader2 className="animate-spin text-muted-foreground" />

    if (reports.length === 0) return <div className="text-muted-foreground">没有找到历史记录。</div>

    return (
        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
            {reports.map((report: any) => (
                <Link key={report.id} href={`/analysis/${report.id}`}>
                    <Card className="hover:shadow-lg transition-shadow cursor-pointer">
                        <CardHeader>
                            <CardTitle className="text-lg">{report.company_name}</CardTitle>
                            <CardDescription>
                                {report.market} {report.symbol}
                            </CardDescription>
                        </CardHeader>
                        <CardContent>
                            <div className="flex items-center justify-between">
                                <span className="text-sm text-muted-foreground">
                                    {new Date(report.created_at).toLocaleString('zh-CN')}
                                </span>
                                <Badge variant={
                                    report.status === "completed" ? "default" :
                                        report.status === "in_progress" ? "secondary" :
                                            report.status === "failed" ? "destructive" : "outline"
                                }>
                                    {report.status === "completed" ? "已完成" :
                                        report.status === "in_progress" ? "进行中" :
                                            report.status === "failed" ? "失败" : "待处理"}
                                </Badge>
                            </div>
                            {report.ai_model && (
                                <div className="mt-2 text-xs text-muted-foreground">
                                    模型: {report.ai_model}
                                </div>
                            )}
                        </CardContent>
                    </Card>
                </Link>
            ))}
        </div>
    )
}
