import { useState } from "react"
import { useAnalysisTemplates } from "@/hooks/useConfig"
import { AnalysisTemplateSets, AnalysisTemplateSet, AnalysisModuleConfig } from "@/types/config"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Separator } from "@/components/ui/separator"
import { Badge } from "@/components/ui/badge"
import { ArrowRight, Box, Layers } from "lucide-react"

export function TemplateTab() {
  const { data: templates, isLoading } = useAnalysisTemplates();
  const [selectedId, setSelectedId] = useState<string | null>(null);

  // Auto select first if none selected
  if (templates && !selectedId && Object.keys(templates).length > 0) {
      setSelectedId(Object.keys(templates)[0]);
  }

  if (isLoading) return <div>Loading templates...</div>;
  if (!templates) return <div>No templates found.</div>;

  const activeTemplate = selectedId ? templates[selectedId] : null;

  return (
    <div className="flex h-[600px] border rounded-md overflow-hidden">
        {/* Sidebar List */}
        <div className="w-[250px] border-r bg-muted/10 flex flex-col">
            <div className="p-4 border-b">
                <h4 className="font-medium mb-1">模板列表</h4>
                <p className="text-xs text-muted-foreground">选择一个分析流程模板进行编辑。</p>
            </div>
            <ScrollArea className="flex-1">
                <div className="p-2 space-y-1">
                    {Object.entries(templates).map(([id, t]) => (
                        <button
                            key={id}
                            onClick={() => setSelectedId(id)}
                            className={`w-full text-left px-3 py-2 rounded-md text-sm transition-colors flex items-center justify-between ${
                                selectedId === id ? "bg-accent text-accent-foreground font-medium" : "hover:bg-muted"
                            }`}
                        >
                            <span>{t.name}</span>
                            {selectedId === id && <ArrowRight className="h-3 w-3 opacity-50" />}
                        </button>
                    ))}
                </div>
            </ScrollArea>
            <div className="p-3 border-t bg-background">
                <Button size="sm" variant="outline" className="w-full">
                    + 新建模板
                </Button>
            </div>
        </div>

        {/* Main Content */}
        <div className="flex-1 bg-background flex flex-col">
            {activeTemplate ? (
                <TemplateDetailView template={activeTemplate} />
            ) : (
                <div className="flex-1 flex items-center justify-center text-muted-foreground">
                    Select a template
                </div>
            )}
        </div>
    </div>
  )
}

function TemplateDetailView({ template }: { template: AnalysisTemplateSet }) {
    return (
        <div className="flex flex-col h-full">
            <div className="p-6 border-b">
                <div className="flex justify-between items-start">
                    <div>
                        <h2 className="text-2xl font-bold tracking-tight">{template.name}</h2>
                        <p className="text-muted-foreground mt-1">
                            包含 {Object.keys(template.modules).length} 个分析模块。
                        </p>
                    </div>
                    <div className="space-x-2">
                        <Button variant="outline">重命名</Button>
                        <Button>保存更改</Button>
                    </div>
                </div>
            </div>
            
            <ScrollArea className="flex-1 p-6">
                <div className="grid gap-6">
                    <div className="flex items-center justify-between">
                        <h3 className="text-lg font-medium flex items-center">
                            <Layers className="mr-2 h-5 w-5" />
                            模块流水线 (Pipeline)
                        </h3>
                        <Button size="sm" variant="secondary">+ 添加模块</Button>
                    </div>
                    
                    {Object.entries(template.modules).map(([moduleId, module]) => (
                        <ModuleCard key={moduleId} id={moduleId} module={module} />
                    ))}
                </div>
            </ScrollArea>
        </div>
    )
}

function ModuleCard({ id, module }: { id: string, module: AnalysisModuleConfig }) {
    return (
        <Card>
            <CardHeader className="pb-3">
                <div className="flex justify-between items-start">
                    <div className="flex items-center gap-2">
                        <div className="bg-primary/10 p-2 rounded-md text-primary">
                            <Box className="h-4 w-4" />
                        </div>
                        <div>
                            <CardTitle className="text-base">{module.name}</CardTitle>
                            <CardDescription className="text-xs font-mono mt-0.5 text-muted-foreground">ID: {id}</CardDescription>
                        </div>
                    </div>
                    <Badge variant="outline" className="font-normal">
                        {module.provider_id} / {module.model_id}
                    </Badge>
                </div>
            </CardHeader>
            <CardContent className="text-sm space-y-4">
                {module.dependencies.length > 0 ? (
                    <div className="flex items-center gap-2 text-muted-foreground text-xs">
                        <span className="font-medium text-foreground">Depends on:</span>
                        {module.dependencies.map(d => (
                            <Badge key={d} variant="secondary" className="h-5 px-1.5 text-[10px]">{d}</Badge>
                        ))}
                    </div>
                ) : (
                    <div className="text-xs text-muted-foreground italic">No dependencies (Root node)</div>
                )}
                
                <div className="bg-muted/30 p-3 rounded-md border">
                    <p className="text-xs font-mono text-muted-foreground truncate">
                        Prompt: {module.prompt_template.substring(0, 50)}...
                    </p>
                </div>
            </CardContent>
        </Card>
    )
}
