"use client";

import { useEffect, useState } from "react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useAnalysisTemplateSets } from "@/hooks/useApi"; // Import the new hook
import type { AnalysisTemplateSets } from "@/types";

type ReportItem = {
    report_id: string;
    created_at?: number;
    score?: number;
    status?: string;
};

export default function QueryPage() {
    const [market, setMarket] = useState<"cn" | "us" | "jp">("cn");
    const [orgId, setOrgId] = useState("600519");
    const [loading, setLoading] = useState(false);
    const [reports, setReports] = useState<ReportItem[]>([]);
    const [msg, setMsg] = useState<string | null>(null);

    // --- New State for Template Selection ---
    const { data: templateSets } = useAnalysisTemplateSets();
    const [selectedTemplateId, setSelectedTemplateId] = useState<string>('');

    // Auto-select first template when available
    useEffect(() => {
        if (templateSets && Object.keys(templateSets).length > 0 && !selectedTemplateId) {
            setSelectedTemplateId(Object.keys(templateSets)[0]);
        }
    }, [templateSets, selectedTemplateId]);


    async function loadReports() {
        if (!market || !orgId) return;
        setLoading(true);
        try {
            // This API seems deprecated, but we keep the logic for now.
            // In a real scenario, this would query the new `analysis_results` table.
            const res = await fetch(`/api/orgs/${market}/${orgId}/reports`);
            const data = await res.json();
            setReports(data.reports ?? []);
        } catch (e) {
            setMsg("加载历史报告失败");
        } finally {
            setLoading(false);
        }
    }

    async function triggerGenerate() {
        if (!orgId || !selectedTemplateId) {
            setMsg("企业ID和分析模板不能为空");
            return;
        }
        setMsg("已触发生成任务…");
        try {
            const res = await fetch(`/api/analysis-requests/${orgId}`, {
                method: "POST",
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ template_id: selectedTemplateId }),
            });
            const data = await res.json();
            if (res.status === 202 && data.request_id) {
                setMsg(`生成任务已入队 (Request ID: ${data.request_id})，请稍后查询结果。`);
                // Simple polling to refresh history
                setTimeout(loadReports, 3000);
            } else {
                const errorMsg = data.error || "触发失败，未知错误。";
                setMsg(`触发失败: ${errorMsg}`);
            }
        } catch (e: any) {
            setMsg(`触发失败: ${e.message || "网络请求错误"}`);
        }
    }

    useEffect(() => {
        loadReports();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    return (
        <div className="space-y-6">
            <header className="space-y-2">
                <h1 className="text-2xl font-semibold">统一查询与分析</h1>
                <p className="text-sm text-muted-foreground">输入企业ID，选择分析模板，触发新报告生成或查询历史报告。</p>
            </header>

            <Card>
                <CardHeader>
                    <CardTitle>查询与分析</CardTitle>
                    <CardDescription>选择市场、企业ID和分析模板来启动一个新的分析任务。</CardDescription>
                </CardHeader>
                <CardContent className="space-y-4">
                    <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                        <div className="space-y-2">
                            <Label>市场</Label>
                            <Select value={market} onValueChange={(v) => setMarket(v as any)}>
                                <SelectTrigger>
                                    <SelectValue />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="cn">中国 (cn)</SelectItem>
                                    <SelectItem value="us">美国 (us)</SelectItem>
                                    <SelectItem value="jp">日本 (jp)</SelectItem>
                                </SelectContent>
                            </Select>
                        </div>
                        <div className="space-y-2">
                            <Label>企业ID</Label>
                            <Input
                                value={orgId}
                                onChange={(e) => setOrgId(e.target.value)}
                                placeholder="输入企业ID，如 600519"
                            />
                        </div>
                        <div className="space-y-2">
                            <Label>分析模板</Label>
                            <Select value={selectedTemplateId} onValueChange={setSelectedTemplateId}>
                                <SelectTrigger>
                                    <SelectValue placeholder="选择一个分析模板..." />
                                </SelectTrigger>
                                <SelectContent>
                                    {templateSets && Object.entries(templateSets).map(([id, set]) => (
                                        <SelectItem key={id} value={id}>{set.name}</SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                        </div>
                    </div>
                    <div className="flex gap-2">
                        <Button onClick={loadReports} disabled={loading}>查询历史</Button>
                        <Button onClick={triggerGenerate} variant="secondary" disabled={!selectedTemplateId}>触发生成</Button>
                    </div>
                    {msg && <p className="text-xs text-muted-foreground pt-2">{msg}</p>}
                </CardContent>
            </Card>

            <Card>
                <CardHeader>
                    <CardTitle>历史报告</CardTitle>
                    <CardDescription>最新在前</CardDescription>
                </CardHeader>
                <CardContent className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
                    {loading && <p>加载中…</p>}
                    {!loading && reports.length === 0 && <p>暂无报告</p>}
                    {reports.map((r) => (
                        <div key={r.report_id} className="border rounded p-3 space-y-2">
                            <div className="flex items-center justify-between">
                                <span className="font-mono text-sm">#{r.report_id}</span>
                                <Badge variant={r.status === "done" ? "secondary" : "outline"}>{r.status ?? "unknown"}</Badge>
                            </div>
                            <div className="text-sm text-muted-foreground">
                                {r.created_at ? new Date(r.created_at * 1000).toLocaleString() : "-"}
                            </div>
                            <div className="text-sm">评分：{r.score ?? "-"}</div>
                            <div className="flex gap-2">
                                <a
                                    className="text-xs underline"
                                    href={`/api/reports/${r.report_id}?market=${market}&org_id=${orgId}`}
                                    target="_blank"
                                    rel="noreferrer"
                                >
                                    查看JSON
                                </a>
                            </div>
                        </div>
                    ))}
                </CardContent>
            </Card>
        </div>
    );
}