"use client"

import { useEffect, useState, use, useRef } from "react"
import { getReport } from "@/lib/api"
import { Badge } from "@/components/ui/badge"
import { Card, CardContent } from "@/components/ui/card"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { MarkdownRenderer } from "@/components/markdown-renderer"
import { Loader2, RefreshCcw, ExternalLink, Download } from "lucide-react"
import { Button } from "@/components/ui/button"

export default function AnalysisPage({ params }: { params: Promise<{ id: string }> }) {
    // Correct way to handle params in Next.js 15+ is async, but we can unwrap or use hook
    // If using 'use client', params corresponds to props which might be a Promise in newer Next.
    // Let's use `use(params)` pattern if React 19, or standard access.
    // Assuming standard Next.js 14/15 behavior for now: props are async.

    // Safety check for React version or just wait for it.
    // simpler: 
    const unwrappedParams = use(params);
    const reportId = parseInt(unwrappedParams.id)

    const [report, setReport] = useState<any>(null)
    const [loading, setLoading] = useState(true)
    const iframeRef = useRef<HTMLIFrameElement>(null)
    const [iframeHeight, setIframeHeight] = useState<number>(800)

    // Polling logic
    useEffect(() => {
        let interval: NodeJS.Timeout;

        const fetchReport = async () => {
            try {
                const data = await getReport(reportId)
                setReport(data)

                if (data.status === "pending" || data.status === "in_progress") {
                    // Poll every 3 seconds
                    interval = setTimeout(fetchReport, 3000)
                } else {
                    setLoading(false)
                }
            } catch (e) {
                console.error(e)
                setLoading(false)
            }
        }

        fetchReport()

        return () => clearTimeout(interval)
    }, [reportId])

    // Listen for height messages from iframe
    useEffect(() => {
        const handleMessage = (event: MessageEvent) => {
            // Accept messages from localhost (for development)
            if (event.data.type === 'resize' && typeof event.data.height === 'number') {
                setIframeHeight(event.data.height + 20) // Add some padding
            }
        }

        window.addEventListener('message', handleMessage)
        return () => window.removeEventListener('message', handleMessage)
    }, [])

    // Handle PDF download
    const handleDownloadPDF = async () => {
        try {
            const response = await fetch(`http://localhost:8000/api/reports/${report.id}/pdf`)
            if (!response.ok) {
                throw new Error('下载失败')
            }
            const blob = await response.blob()
            const url = window.URL.createObjectURL(blob)
            const a = document.createElement('a')
            a.href = url
            a.download = `${report.company_name}_${report.symbol}_分析报告.pdf`
            document.body.appendChild(a)
            a.click()
            window.URL.revokeObjectURL(url)
            document.body.removeChild(a)
        } catch (error) {
            console.error('PDF下载失败:', error)
            alert('PDF下载失败，请稍后重试')
        }
    }

    if (loading && !report) return <div className="flex h-screen items-center justify-center"><Loader2 className="animate-spin h-8 w-8 text-primary" /></div>

    if (!report) return <div className="p-8">未找到报告。</div>

    return (
        <div className="container mx-auto py-8 px-4 space-y-6 max-w-7xl">
            <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
                <div>
                    <h1 className="text-3xl font-bold tracking-tight">{report.company_name}</h1>
                    <p className="text-muted-foreground mt-2">
                        {report.market} {report.symbol} · {new Date(report.created_at).toLocaleString('zh-CN')}
                        {report.ai_model && <span className="ml-2">· 模型: {report.ai_model}</span>}
                    </p>
                </div>
                <div className="flex items-center gap-4">
                    <Badge variant={
                        report.status === "completed" ? "default" :
                            report.status === "in_progress" ? "secondary" :
                                report.status === "failed" ? "destructive" : "outline"
                    }>
                        {report.status === "in_progress" ? (
                            <div className="flex items-center gap-2">
                                <Loader2 className="h-3 w-3 animate-spin" /> 进行中
                            </div>
                        ) : report.status === "completed" ? "已完成" : report.status === "failed" ? "失败" : report.status === "pending" ? "待处理" : report.status}
                    </Badge>
                    {report.status === "completed" && (
                        <Button onClick={handleDownloadPDF} variant="outline" size="sm">
                            <Download className="h-4 w-4 mr-2" />
                            下载 PDF
                        </Button>
                    )}
                </div>
            </div>

            <Tabs defaultValue="financial_data" className="space-y-4">
                <TabsList className="bg-muted/50 p-1 flex-wrap h-auto">
                    <TabsTrigger value="financial_data">财务数据</TabsTrigger>

                    {[
                        { id: 'company_profile', label: '公司简介' },
                        { id: 'fundamental_analysis', label: '基本面分析' },
                        { id: 'insider_analysis', label: '内部人士分析' },
                        { id: 'bullish_analysis', label: '看涨分析' },
                        { id: 'bearish_analysis', label: '看跌分析' }
                    ].map((section) => (
                        <div key={section.id} className="flex items-center">
                            <div className="h-4 w-[1px] bg-border mx-1" />
                            <TabsTrigger value={section.id} className="capitalize">
                                {section.label}
                            </TabsTrigger>
                        </div>
                    ))}
                </TabsList>

                <TabsContent value="financial_data" className="min-h-[500px]">
                    <Card style={{ height: `${iframeHeight}px` }}>
                        <iframe
                            ref={iframeRef}
                            src={`http://localhost:8000/api/reports/${report.id}/html`}
                            className="w-full h-full border-0 rounded-md"
                            title="分析仪表板"
                        />
                    </Card>
                </TabsContent>

                {[
                    { id: 'company_profile', label: '公司简介' },
                    { id: 'fundamental_analysis', label: '基本面分析' },
                    { id: 'insider_analysis', label: '内部人士分析' },
                    { id: 'bullish_analysis', label: '看涨分析' },
                    { id: 'bearish_analysis', label: '看跌分析' }
                ].map((section) => {
                    const sectionData = report.sections?.find((s: any) => s.section_name === section.id);
                    return (
                        <TabsContent key={section.id} value={section.id} className="min-h-[500px]">
                            <Card>
                                <CardContent className="p-6 md:p-8">
                                    {sectionData ? (
                                        <MarkdownRenderer content={sectionData.content} />
                                    ) : (
                                        <div className="flex flex-col items-center justify-center py-20 text-muted-foreground">
                                            {report.status === "in_progress" || report.status === "pending" ? (
                                                <>
                                                    <Loader2 className="h-10 w-10 animate-spin mb-4 text-primary" />
                                                    <p>AI 正在撰写{section.label}...</p>
                                                    <p className="text-sm mt-2 opacity-75">请稍候，全面分析通常需要 1 分钟左右</p>
                                                </>
                                            ) : (
                                                <p>该部分暂无内容</p>
                                            )}
                                        </div>
                                    )}
                                </CardContent>
                            </Card>
                        </TabsContent>
                    );
                })}
            </Tabs>
        </div>
    )
}
