import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle, CardFooter } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { BarChart3, Search, Sparkles, Loader2 } from "lucide-react"
import { useAnalysisTemplates } from "@/hooks/useConfig"

export function Dashboard() {
  const navigate = useNavigate();
  const [symbol, setSymbol] = useState("");
  const [market, setMarket] = useState("CN");
  const [templateId, setTemplateId] = useState("");

  const { data: templates, isLoading: isTemplatesLoading } = useAnalysisTemplates();

  // Auto-select first template when loaded
  useEffect(() => {
      if (templates && Object.keys(templates).length > 0 && !templateId) {
          setTemplateId(Object.keys(templates)[0]);
      }
  }, [templates, templateId]);

  const handleStart = () => {
    if (!symbol || !templateId) return;
    // In real app, we would POST to create a workflow, get ID, then navigate.
    // Here we just mock an ID.
    const mockRequestId = "req-" + Math.random().toString(36).substr(2, 9);
    navigate(`/report/${mockRequestId}?symbol=${symbol}&market=${market}&templateId=${templateId}`);
  };

  return (
    <div className="flex flex-col items-center justify-center min-h-[calc(100vh-4rem)] bg-muted/5 px-4">
      <div className="w-full max-w-3xl space-y-8 text-center">
         <div className="space-y-2">
            <h1 className="text-4xl font-extrabold tracking-tight lg:text-5xl bg-gradient-to-r from-primary to-primary/60 bg-clip-text text-transparent">
                Fundamental Analysis
            </h1>
            <p className="text-xl text-muted-foreground">
                基于 AI Agent 的深度基本面投研平台
            </p>
         </div>

         <Card className="w-full max-w-xl mx-auto shadow-lg border-primary/10">
            <CardHeader>
                <CardTitle className="flex items-center justify-center gap-2">
                    <Sparkles className="h-5 w-5 text-yellow-500" />
                    开始新的分析
                </CardTitle>
                <CardDescription>
                    输入股票代码，自动聚合多源数据并生成深度报告。
                </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
                <div className="grid grid-cols-4 gap-4">
                    <div className="col-span-3 space-y-2 text-left">
                        <Label htmlFor="symbol">股票代码 (Symbol)</Label>
                        <div className="relative">
                            <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
                            <Input 
                                id="symbol" 
                                placeholder="e.g. 600519.SS or AAPL" 
                                className="pl-9"
                                value={symbol}
                                onChange={(e) => setSymbol(e.target.value)}
                            />
                        </div>
                    </div>
                    <div className="col-span-1 space-y-2 text-left">
                        <Label htmlFor="market">市场 (Market)</Label>
                        <Select value={market} onValueChange={setMarket}>
                            <SelectTrigger id="market">
                                <SelectValue placeholder="Market" />
                            </SelectTrigger>
                            <SelectContent>
                                <SelectItem value="CN">CN (A股)</SelectItem>
                                <SelectItem value="US">US (美股)</SelectItem>
                                <SelectItem value="HK">HK (港股)</SelectItem>
                            </SelectContent>
                        </Select>
                    </div>
                </div>

                <div className="space-y-2 text-left">
                    <Label htmlFor="template">分析模板 (Template)</Label>
                    <Select value={templateId} onValueChange={setTemplateId} disabled={isTemplatesLoading}>
                        <SelectTrigger id="template">
                            <SelectValue placeholder={isTemplatesLoading ? "Loading templates..." : "Select a template"} />
                        </SelectTrigger>
                        <SelectContent>
                            {templates ? (
                                Object.entries(templates).map(([id, t]) => (
                                    <SelectItem key={id} value={id}>
                                        {t.name}
                                    </SelectItem>
                                ))
                            ) : (
                                <SelectItem value="loading" disabled>Loading...</SelectItem>
                            )}
                        </SelectContent>
                    </Select>
                </div>

            </CardContent>
            <CardFooter>
                <Button size="lg" className="w-full text-base" onClick={handleStart} disabled={!symbol || !templateId || isTemplatesLoading}>
                    {isTemplatesLoading ? <Loader2 className="mr-2 h-5 w-5 animate-spin" /> : <BarChart3 className="mr-2 h-5 w-5" />}
                    生成分析报告
                </Button>
            </CardFooter>
         </Card>

         <div className="grid grid-cols-1 md:grid-cols-3 gap-4 max-w-4xl mx-auto text-left">
             <FeatureCard title="多源数据聚合" desc="集成 Tushare, Finnhub 等多个专业金融数据源。" />
             <FeatureCard title="AI 驱动分析" desc="使用 GPT-4o 等大模型进行深度财务指标解读。" />
             <FeatureCard title="可视化工作流" desc="全流程透明化，实时查看每个分析步骤的状态。" />
         </div>
      </div>
    </div>
  )
}

function FeatureCard({ title, desc }: { title: string, desc: string }) {
    return (
        <div className="p-4 rounded-lg border bg-card text-card-foreground shadow-sm">
            <h3 className="font-semibold mb-1">{title}</h3>
            <p className="text-sm text-muted-foreground">{desc}</p>
        </div>
    )
}
