"use client"

import { useCallback, useMemo, useState } from "react"
import { TrendingUp, FileText, Sparkles } from "lucide-react"
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card"
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs"
import { Button } from "@/components/ui/button"
import { Textarea } from "@/components/ui/textarea"
import TaskList from "@/components/ai-assistant/task-list"
import CreateTaskDialog from "@/components/ai-assistant/create-task-dialog"
import ReportCards from "@/components/ai-assistant/report-cards"
import { sanitizeText } from "@/lib/text-sanitize"
import type { AnalysisTask, ReportItem, ReportTemplate } from "@/types/ai-assistant"

const initialTasks: AnalysisTask[] = [
  {
    id: "task_001",
    name: "用户资产价值评估报告",
    database: "用户池数据",
    status: "completed",
    progress: 100,
    createdAt: "2025-01-15T09:00:00Z",
    completedAt: "2025-01-15T09:30:00Z",
    reportUrl: "/reports/user-asset-evaluation.pdf",
    description: "基于RFM模型和行为数据的用户资产价值评估",
  },
  {
    id: "task_002",
    name: "高价值用户画像分析",
    database: "用户池数据",
    status: "running",
    progress: 65,
    createdAt: "2025-01-15T10:00:00Z",
    description: "识别高价值用户特征和行为模式",
  },
  {
    id: "task_003",
    name: "用户生命周期价值预测",
    database: "用户池数据",
    status: "pending",
    progress: 0,
    createdAt: "2025-01-15T10:30:00Z",
    description: "预测用户未来价值和流失风险",
  },
]

const templates: ReportTemplate[] = [
  {
    id: "template_001",
    name: "用户资产评估报告",
    description: "全面评估用户资产价值和投资回报",
    category: "资产评估",
    fields: ["资产总值", "RFM分析", "价值分层", "投资回报", "增值建议"],
    isEditable: true,
  },
  {
    id: "template_002",
    name: "用户价值分析报告",
    description: "深度分析用户价值构成和增长潜力",
    category: "价值分析",
    fields: ["价值构成", "增长趋势", "潜力评估", "风险分析", "优化策略"],
    isEditable: true,
  },
  {
    id: "template_003",
    name: "用户生命周期报告",
    description: "分析用户生命周期各阶段的价值贡献",
    category: "生命周期",
    fields: ["阶段划分", "价值贡献", "转化率", "留存分析", "提升方案"],
    isEditable: true,
  },
]

const reportItems: ReportItem[] = [
  {
    id: "rpt-1",
    title: "用户资产评估报告",
    source: "数据源：用户池",
    description: "基于用户行为和交易数据，评估用户资产价值和投资回报率。",
    updatedAt: new Date().toISOString(),
  },
  {
    id: "rpt-2",
    title: "高价值用户分析",
    source: "数据源：用户池",
    description: "识别和分析高价值用户的特征、行为模式和价值贡献。",
    updatedAt: new Date().toISOString(),
  },
  {
    id: "rpt-3",
    title: "用户价值预测模型",
    source: "数据源：用户池",
    description: "基于机器学习预测用户未来价值和生命周期价值。",
    updatedAt: new Date().toISOString(),
  },
]

export default function AIAssistantPage() {
  const [tasks, setTasks] = useState<AnalysisTask[]>(initialTasks)
  const [editingTemplate, setEditingTemplate] = useState<string | null>(null)
  const [templateContent, setTemplateContent] = useState<string>("")

  const tick = useCallback(() => {
    setTasks((prev) =>
      prev.map((t) => {
        if (t.status === "running" && t.progress < 100) {
          const p = Math.min(100, t.progress + Math.random() * 12)
          if (p >= 100) {
            return {
              ...t,
              progress: 100,
              status: "completed",
              completedAt: new Date().toISOString(),
              reportUrl: `/reports/${t.id}.pdf`,
            }
          }
          return { ...t, progress: p }
        }
        return t
      }),
    )
  }, [])

  const onCreate = (task: AnalysisTask) => {
    setTasks((prev) => [task, ...prev])
    // 模拟启动
    setTimeout(() => {
      setTasks((prev) => prev.map((t) => (t.id === task.id ? { ...t, status: "running" } : t)))
    }, 800)
  }

  const handleEditTemplate = (templateId: string) => {
    setEditingTemplate(templateId)
    const template = templates.find((t) => t.id === templateId)
    setTemplateContent(template?.fields.join("\n") || "")
  }

  const handleSaveTemplate = () => {
    // 保存模板逻辑
    setEditingTemplate(null)
    setTemplateContent("")
  }

  const sanitizedItems = useMemo(() => reportItems.map((i) => ({ ...i, description: sanitizeText(i.description) })), [])

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-white to-indigo-50">
      <div className="container mx-auto px-4 py-8">
        <div className="mb-6">
          <h1 className="text-3xl font-bold flex items-center gap-2">
            <Sparkles className="h-8 w-8 text-blue-500" />
            AI智能助手
          </h1>
          <p className="text-gray-600">专注用户资产评估与价值分析</p>
        </div>

        <Tabs defaultValue="analysis" className="space-y-6">
          <TabsList className="grid w-full grid-cols-2">
            <TabsTrigger value="analysis" className="flex items-center gap-2">
              <TrendingUp className="w-4 h-4" />
              用户资产评估
            </TabsTrigger>
            <TabsTrigger value="templates" className="flex items-center gap-2">
              <FileText className="w-4 h-4" />
              报告模板
            </TabsTrigger>
          </TabsList>

          <TabsContent value="analysis" className="space-y-6">
            <div className="flex items-center justify-between">
              <h2 className="text-xl font-semibold">用户资产分析任务</h2>
              <CreateTaskDialog databases={[]} templates={templates} onCreate={onCreate} />
            </div>

            <TaskList tasks={tasks} onTick={tick} />

            <ReportCards items={sanitizedItems} />
          </TabsContent>

          <TabsContent value="templates">
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <FileText className="w-4 h-4" />
                  可编辑报告模板
                </CardTitle>
              </CardHeader>
              <CardContent className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                {templates.map((t) => (
                  <Card key={t.id} className="border">
                    <CardContent className="p-4 space-y-2">
                      <div className="font-medium">{t.name}</div>
                      <div className="text-sm text-gray-600">{t.category}</div>
                      <div className="text-xs text-gray-500">{t.description}</div>
                      {editingTemplate === t.id ? (
                        <div className="space-y-2">
                          <Textarea
                            value={templateContent}
                            onChange={(e) => setTemplateContent(e.target.value)}
                            placeholder="编辑模板字段..."
                            className="text-xs"
                          />
                          <div className="flex gap-2">
                            <Button size="sm" onClick={handleSaveTemplate}>
                              保存
                            </Button>
                            <Button size="sm" variant="outline" onClick={() => setEditingTemplate(null)}>
                              取消
                            </Button>
                          </div>
                        </div>
                      ) : (
                        <Button size="sm" variant="outline" onClick={() => handleEditTemplate(t.id)} className="w-full">
                          编辑模板
                        </Button>
                      )}
                    </CardContent>
                  </Card>
                ))}
              </CardContent>
            </Card>
          </TabsContent>
        </Tabs>
      </div>
    </div>
  )
}
