"use client"

import { useState } from "react"
import { searchStock, startAnalysis } from "@/lib/api"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
import { Search, Loader2 } from "lucide-react"
import { useRouter } from "next/navigation"

export function SearchStock() {
    const [query, setQuery] = useState("")
    const [results, setResults] = useState<{ market: string; symbol: string; company_name: string }[]>([])
    const [loading, setLoading] = useState(false)
    const [error, setError] = useState("")
    const router = useRouter()

    const handleSearch = async () => {
        if (!query.trim()) return
        setLoading(true)
        setError("")
        setResults([])

        try {
            const data = await searchStock(query)
            setResults(data)
        } catch (err: any) {
            setError(err.message || "搜索失败")
        } finally {
            setLoading(false)
        }
    }

    const handleAnalyze = async (result: { market: string; symbol: string; company_name: string }) => {
        setLoading(true)
        try {
            const report = await startAnalysis(result.market, result.symbol, result.company_name)
            router.push(`/analysis/${report.id}`)
        } catch (err: any) {
            setError(err.message || "启动分析失败")
        } finally {
            setLoading(false)
        }
    }

    return (
        <Card className="w-full max-w-2xl">
            <CardHeader>
                <CardTitle>开始新的分析</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
                <div className="flex gap-2">
                    <Input
                        placeholder="输入公司名称（例如：腾讯）或代码（例如：700）"
                        value={query}
                        onChange={(e) => setQuery(e.target.value)}
                        onKeyDown={(e) => e.key === "Enter" && handleSearch()}
                    />
                    <Button onClick={handleSearch} disabled={loading}>
                        {loading ? <Loader2 className="animate-spin" /> : <Search />}
                    </Button>
                </div>

                {error && <div className="text-red-500 text-sm">{error}</div>}

                {results.length > 0 && (
                    <div className="space-y-2">
                        {results.length > 1 && (
                            <div className="text-sm text-muted-foreground">找到 {results.length} 个结果，请选择：</div>
                        )}
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                            {results.map((result, index) => (
                                <div key={index} className="bg-muted p-3 rounded-md space-y-2 border hover:border-primary transition-colors">
                                    <div className="font-medium">{result.company_name}</div>
                                    <div className="text-xs text-muted-foreground">
                                        {result.market} | {result.symbol}
                                    </div>
                                    <Button onClick={() => handleAnalyze(result)} disabled={loading} className="w-full" size="sm">
                                        {loading ? "正在启动分析..." : "运行分析"}
                                    </Button>
                                </div>
                            ))}
                        </div>
                    </div>
                )}
            </CardContent>
        </Card>
    )
}
