"use client"

import { useState, useEffect } from "react"
import { getConfig, updateConfig } from "@/lib/api"
import { Card, CardContent, CardHeader, CardTitle, CardDescription, CardFooter } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Loader2 } from "lucide-react"

export default function ConfigPage() {
    const [config, setConfig] = useState<any>({})
    const [loading, setLoading] = useState(true)
    const [saving, setSaving] = useState(false)
    const [message, setMessage] = useState("")

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

    const handleSave = async (key: string, value: string) => {
        setSaving(true)
        try {
            await updateConfig(key, value)
            setMessage(`Saved ${key}`)
            // Update local state
            setConfig((prev: any) => ({ ...prev, [key]: value }))
        } catch (e) {
            setMessage("Error saving settings")
        } finally {
            setSaving(false)
            setTimeout(() => setMessage(""), 3000)
        }
    }

    if (loading) return <div className="p-8 flex justify-center"><Loader2 className="animate-spin" /></div>

    const prompts = [
        "company_profile", "fundamental_analysis", "insider_analysis", "bullish_analysis", "bearish_analysis"
    ]

    return (
        <div className="container mx-auto py-10 space-y-8 max-w-4xl">
            <h1 className="text-3xl font-bold">配置</h1>

            <Card>
                <CardHeader>
                    <CardTitle>系统设置</CardTitle>
                    <CardDescription>配置 API 密钥和数据库连接。</CardDescription>
                </CardHeader>
                <CardContent className="space-y-4">
                    <div className="space-y-2">
                        <Label>Gemini API 密钥</Label>
                        <div className="flex gap-2">
                            <Input
                                type="password"
                                value={config["GEMINI_API_KEY"] || ""}
                                onChange={(e) => setConfig({ ...config, "GEMINI_API_KEY": e.target.value })}
                                placeholder="****************"
                            />
                            <Button onClick={() => handleSave("GEMINI_API_KEY", config["GEMINI_API_KEY"])}>保存</Button>
                        </div>
                    </div>

                    <div className="space-y-2">
                        <Label>AI 模型</Label>
                        <div className="flex gap-2">
                            <select
                                className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
                                value={config["AI_MODEL"] || "gemini-2.0-flash"}
                                onChange={(e) => setConfig({ ...config, "AI_MODEL": e.target.value })}
                            >
                                <option value="gemini-2.0-flash">Gemini 2.0 Flash</option>
                                <option value="gemini-2.5-flash">Gemini 2.5 Flash</option>
                                <option value="gemini-3-flash-preview">Gemini 3 Flash Preview</option>
                                <option value="gemini-3-pro-preview">Gemini 3 Pro Preview</option>
                                <option value="custom">自定义模型...</option>
                            </select>
                            <Button onClick={() => handleSave("AI_MODEL", config["AI_MODEL"])}>保存</Button>
                        </div>
                        {config["AI_MODEL"] === "custom" && (
                            <div className="mt-2">
                                <Input
                                    placeholder="输入自定义模型名称，例如：gemini-1.5-pro"
                                    value={config["AI_MODEL_CUSTOM"] || ""}
                                    onChange={(e) => {
                                        setConfig({ ...config, "AI_MODEL_CUSTOM": e.target.value, "AI_MODEL": e.target.value })
                                    }}
                                />
                            </div>
                        )}
                        <p className="text-xs text-muted-foreground">
                            选择用于分析的 AI 模型。推荐使用 Gemini 2.0 Flash 以获得最佳性能和速度。
                        </p>
                    </div>
                </CardContent>
            </Card>

            <Card>
                <CardHeader>
                    <CardTitle>分析提示词</CardTitle>
                    <CardDescription>自定义每个分析步骤使用的提示词。</CardDescription>
                </CardHeader>
                <CardContent className="space-y-6">
                    {prompts.map(key => (
                        <div key={key} className="space-y-2">
                            <Label className="capitalize">{key.replace(/_/g, " ")}</Label>
                            <div className="flex flex-col gap-2">
                                <Textarea
                                    className="min-h-[150px] font-mono text-sm"
                                    value={config[`PROMPT_${key.toUpperCase()}`] || ""}
                                    onChange={(e) => setConfig({ ...config, [`PROMPT_${key.toUpperCase()}`]: e.target.value })}
                                    placeholder={`Enter prompt for ${key}...`}
                                />
                                <Button
                                    className="w-fit"
                                    variant="outline"
                                    onClick={() => handleSave(`PROMPT_${key.toUpperCase()}`, config[`PROMPT_${key.toUpperCase()}`])}
                                >
                                    保存 {key.replace(/_/g, " ")}
                                </Button>
                            </div>
                        </div>
                    ))}
                </CardContent>
            </Card>

            {message && <div className="fixed bottom-4 right-4 bg-primary text-primary-foreground px-4 py-2 rounded shadow-lg animate-in fade-in slide-in-from-bottom-5">
                {message.replace('Saved', '已保存').replace('Error saving settings', '保存设置时出错')}
            </div>}
        </div>
    )
}
