"use client"

import { useState } from "react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Progress } from "@/components/ui/progress"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import {
  Brain,
  TrendingUp,
  AlertTriangle,
  Zap,
  Filter,
  RefreshCw,
  Download,
  ChevronRight,
  ChevronDown,
} from "lucide-react"
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"

export default function AIAnalysisPage() {
  const [timeRange, setTimeRange] = useState("today")
  const [expandedSections, setExpandedSections] = useState({
    overview: true,
    trends: true,
    anomaly: false,
    predictions: false,
  })

  // AI分析数据
  const aiData = {
    overview: {
      totalInsights: 156,
      trendsIdentified: 23,
      anomaliesDetected: 3,
      predictionsGenerated: 89,
      accuracy: 94.2,
      modelPerformance: 97.8,
    },
    trendAnalysis: [
      {
        trend: "用户活跃度上升趋势",
        confidence: 95.8,
        impact: "高",
        timeframe: "未来7天",
        description: "基于用户行为模式分析，预测用户活跃度将持续上升",
        recommendation: "增加内容推送频率，优化用户体验",
      },
      {
        trend: "移动端使用增长",
        confidence: 89.2,
        impact: "中高",
        timeframe: "未来14天",
        description: "移动端用户访问量呈现明显增长趋势",
        recommendation: "优化移动端界面，提升响应速度",
      },
      {
        trend: "高价值用户转化提升",
        confidence: 92.5,
        impact: "高",
        timeframe: "未来30天",
        description: "高价值用户转化率预计将显著提升",
        recommendation: "制定针对性营销策略，加强用户维护",
      },
    ],
    anomalyDetection: [
      {
        type: "流量异常",
        severity: "中等",
        detected: "今天 13:45",
        description: "检测到异常流量峰值，比平时高出45%",
        status: "已处理",
        action: "已启动自动扩容机制",
      },
      {
        type: "用户行为异常",
        severity: "低",
        detected: "今天 11:20",
        description: "部分用户群体行为模式发生变化",
        status: "监控中",
        action: "持续观察用户行为变化",
      },
      {
        type: "数据质量异常",
        severity: "高",
        detected: "今天 09:15",
        description: "数据源同步出现延迟，影响实时分析",
        status: "已修复",
        action: "已重新同步数据，恢复正常",
      },
    ],
    predictiveModels: [
      {
        model: "用户流失预测模型",
        accuracy: 94.2,
        lastTrained: "今天 06:00",
        predictions: 1245,
        status: "运行中",
        description: "预测用户流失风险，准确率达94.2%",
      },
      {
        model: "价值提升预测模型",
        accuracy: 91.8,
        lastTrained: "今天 05:30",
        predictions: 856,
        status: "运行中",
        description: "预测用户价值提升潜力，指导运营策略",
      },
      {
        model: "内容推荐模型",
        accuracy: 87.5,
        lastTrained: "今天 04:45",
        predictions: 2341,
        status: "运行中",
        description: "个性化内容推荐，提升用户参与度",
      },
    ],
  }

  const toggleSection = (section: string) => {
    setExpandedSections((prev) => ({
      ...prev,
      [section]: !prev[section],
    }))
  }

  const getImpactColor = (impact: string) => {
    switch (impact) {
      case "高":
        return "bg-red-100 text-red-800"
      case "中高":
        return "bg-orange-100 text-orange-800"
      case "中":
        return "bg-yellow-100 text-yellow-800"
      case "低":
        return "bg-green-100 text-green-800"
      default:
        return "bg-gray-100 text-gray-800"
    }
  }

  const getSeverityColor = (severity: string) => {
    switch (severity) {
      case "高":
        return "bg-red-100 text-red-800"
      case "中等":
        return "bg-yellow-100 text-yellow-800"
      case "低":
        return "bg-green-100 text-green-800"
      default:
        return "bg-gray-100 text-gray-800"
    }
  }

  const getStatusColor = (status: string) => {
    switch (status) {
      case "运行中":
        return "bg-green-100 text-green-800"
      case "已处理":
        return "bg-blue-100 text-blue-800"
      case "监控中":
        return "bg-yellow-100 text-yellow-800"
      case "已修复":
        return "bg-green-100 text-green-800"
      default:
        return "bg-gray-100 text-gray-800"
    }
  }

  return (
    <div className="container mx-auto py-4 md:py-6 space-y-4 md:space-y-6">
      {/* 页面标题和工具栏 */}
      <div className="flex flex-col md:flex-row md:justify-between md:items-center gap-4">
        <div>
          <h1 className="text-2xl md:text-3xl font-bold">AI分析</h1>
          <p className="text-sm md:text-base text-muted-foreground mt-1">智能数据洞察与预测分析</p>
        </div>
        <div className="flex flex-wrap gap-2">
          <Select value={timeRange} onValueChange={setTimeRange}>
            <SelectTrigger className="w-[120px] text-sm">
              <SelectValue placeholder="时间范围" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="today">今日</SelectItem>
              <SelectItem value="week">本周</SelectItem>
              <SelectItem value="month">本月</SelectItem>
            </SelectContent>
          </Select>
          <Button variant="outline" size="icon" className="h-9 w-9 bg-transparent">
            <Filter className="h-4 w-4" />
          </Button>
          <Button variant="outline" size="icon" className="h-9 w-9 bg-transparent">
            <RefreshCw className="h-4 w-4" />
          </Button>
          <Button variant="outline" size="sm" className="hidden md:flex bg-transparent">
            <Download className="mr-2 h-4 w-4" />
            导出
          </Button>
        </div>
      </div>

      {/* AI分析概览 */}
      <Collapsible
        open={expandedSections.overview}
        onOpenChange={(open) => setExpandedSections((prev) => ({ ...prev, overview: open }))}
      >
        <Card className="border-none shadow-md">
          <CollapsibleTrigger className="w-full">
            <CardHeader className="bg-gradient-to-r from-purple-50 to-pink-50 border-b hover:from-purple-100 hover:to-pink-100 transition-colors cursor-pointer py-3 md:py-4">
              <div className="flex justify-between items-center">
                <div className="flex items-center gap-3">
                  <Brain className="h-4 w-4 md:h-5 md:w-5 text-purple-600" />
                  <div className="text-left">
                    <CardTitle className="text-base md:text-lg">AI分析概览</CardTitle>
                    <CardDescription className="text-xs md:text-sm">智能分析引擎运行状态</CardDescription>
                  </div>
                </div>
                {expandedSections.overview ? (
                  <ChevronDown className="h-4 w-4 md:h-5 md:w-5" />
                ) : (
                  <ChevronRight className="h-4 w-4 md:h-5 md:w-5" />
                )}
              </div>
            </CardHeader>
          </CollapsibleTrigger>
          <CollapsibleContent>
            <CardContent className="p-4">
              <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3 md:gap-4">
                <div className="bg-purple-50 p-3 rounded-lg text-center">
                  <div className="text-lg md:text-2xl font-bold text-purple-600">{aiData.overview.totalInsights}</div>
                  <div className="text-xs text-purple-700">AI洞察</div>
                </div>
                <div className="bg-blue-50 p-3 rounded-lg text-center">
                  <div className="text-lg md:text-2xl font-bold text-blue-600">{aiData.overview.trendsIdentified}</div>
                  <div className="text-xs text-blue-700">趋势识别</div>
                </div>
                <div className="bg-orange-50 p-3 rounded-lg text-center">
                  <div className="text-lg md:text-2xl font-bold text-orange-600">
                    {aiData.overview.anomaliesDetected}
                  </div>
                  <div className="text-xs text-orange-700">异常检测</div>
                </div>
                <div className="bg-green-50 p-3 rounded-lg text-center">
                  <div className="text-lg md:text-2xl font-bold text-green-600">
                    {aiData.overview.predictionsGenerated}
                  </div>
                  <div className="text-xs text-green-700">预测生成</div>
                </div>
                <div className="bg-indigo-50 p-3 rounded-lg text-center">
                  <div className="text-lg md:text-2xl font-bold text-indigo-600">{aiData.overview.accuracy}%</div>
                  <div className="text-xs text-indigo-700">预测准确率</div>
                </div>
                <div className="bg-pink-50 p-3 rounded-lg text-center">
                  <div className="text-lg md:text-2xl font-bold text-pink-600">{aiData.overview.modelPerformance}%</div>
                  <div className="text-xs text-pink-700">模型性能</div>
                </div>
              </div>
            </CardContent>
          </CollapsibleContent>
        </Card>
      </Collapsible>

      {/* 趋势识别 */}
      <Collapsible
        open={expandedSections.trends}
        onOpenChange={(open) => setExpandedSections((prev) => ({ ...prev, trends: open }))}
      >
        <Card className="border-none shadow-md">
          <CollapsibleTrigger className="w-full">
            <CardHeader className="bg-gradient-to-r from-blue-50 to-indigo-50 border-b hover:from-blue-100 hover:to-indigo-100 transition-colors cursor-pointer py-3 md:py-4">
              <div className="flex justify-between items-center">
                <div className="flex items-center gap-3">
                  <TrendingUp className="h-4 w-4 md:h-5 md:w-5 text-blue-600" />
                  <div className="text-left">
                    <CardTitle className="text-base md:text-lg">趋势识别</CardTitle>
                    <CardDescription className="text-xs md:text-sm">AI驱动的趋势预测分析</CardDescription>
                  </div>
                </div>
                {expandedSections.trends ? (
                  <ChevronDown className="h-4 w-4 md:h-5 md:w-5" />
                ) : (
                  <ChevronRight className="h-4 w-4 md:h-5 md:w-5" />
                )}
              </div>
            </CardHeader>
          </CollapsibleTrigger>
          <CollapsibleContent>
            <CardContent className="p-4">
              <div className="space-y-3">
                {aiData.trendAnalysis.map((trend, index) => (
                  <div key={index} className="bg-white border rounded-lg p-3 md:p-4">
                    <div className="flex flex-col md:flex-row md:items-start justify-between gap-3">
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-2">
                          <h3 className="font-medium text-sm md:text-base">{trend.trend}</h3>
                          <Badge className={getImpactColor(trend.impact)}>{trend.impact}影响</Badge>
                        </div>
                        <p className="text-xs md:text-sm text-gray-600 mb-2">{trend.description}</p>
                        <p className="text-xs text-blue-600 font-medium">建议: {trend.recommendation}</p>
                      </div>
                      <div className="flex flex-col md:items-end gap-2">
                        <div className="text-right">
                          <div className="text-sm font-bold text-green-600">{trend.confidence}%</div>
                          <div className="text-xs text-gray-500">置信度</div>
                        </div>
                        <div className="text-right">
                          <div className="text-sm font-medium">{trend.timeframe}</div>
                          <div className="text-xs text-gray-500">预测时间</div>
                        </div>
                      </div>
                    </div>
                    <div className="mt-3">
                      <div className="flex justify-between text-xs mb-1">
                        <span>置信度</span>
                        <span>{trend.confidence}%</span>
                      </div>
                      <Progress value={trend.confidence} className="h-1.5" />
                    </div>
                  </div>
                ))}
              </div>
            </CardContent>
          </CollapsibleContent>
        </Card>
      </Collapsible>

      {/* 异常检测 */}
      <Collapsible
        open={expandedSections.anomaly}
        onOpenChange={(open) => setExpandedSections((prev) => ({ ...prev, anomaly: open }))}
      >
        <Card className="border-none shadow-md">
          <CollapsibleTrigger className="w-full">
            <CardHeader className="bg-gradient-to-r from-orange-50 to-red-50 border-b hover:from-orange-100 hover:to-red-100 transition-colors cursor-pointer py-3 md:py-4">
              <div className="flex justify-between items-center">
                <div className="flex items-center gap-3">
                  <AlertTriangle className="h-4 w-4 md:h-5 md:w-5 text-orange-600" />
                  <div className="text-left">
                    <CardTitle className="text-base md:text-lg">异常检测</CardTitle>
                    <CardDescription className="text-xs md:text-sm">智能异常监控与预警</CardDescription>
                  </div>
                </div>
                {expandedSections.anomaly ? (
                  <ChevronDown className="h-4 w-4 md:h-5 md:w-5" />
                ) : (
                  <ChevronRight className="h-4 w-4 md:h-5 md:w-5" />
                )}
              </div>
            </CardHeader>
          </CollapsibleTrigger>
          <CollapsibleContent>
            <CardContent className="p-4">
              <div className="space-y-3">
                {aiData.anomalyDetection.map((anomaly, index) => (
                  <div key={index} className="bg-white border rounded-lg p-3 md:p-4">
                    <div className="flex flex-col md:flex-row md:items-center justify-between gap-3">
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-2">
                          <h3 className="font-medium text-sm md:text-base">{anomaly.type}</h3>
                          <Badge className={getSeverityColor(anomaly.severity)}>{anomaly.severity}</Badge>
                          <Badge className={getStatusColor(anomaly.status)}>{anomaly.status}</Badge>
                        </div>
                        <p className="text-xs md:text-sm text-gray-600 mb-2">{anomaly.description}</p>
                        <p className="text-xs text-blue-600 font-medium">处理措施: {anomaly.action}</p>
                      </div>
                      <div className="text-right">
                        <div className="text-sm font-medium">{anomaly.detected}</div>
                        <div className="text-xs text-gray-500">检测时间</div>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </CardContent>
          </CollapsibleContent>
        </Card>
      </Collapsible>

      {/* 预测模型 */}
      <Collapsible
        open={expandedSections.predictions}
        onOpenChange={(open) => setExpandedSections((prev) => ({ ...prev, predictions: open }))}
      >
        <Card className="border-none shadow-md">
          <CollapsibleTrigger className="w-full">
            <CardHeader className="bg-gradient-to-r from-green-50 to-emerald-50 border-b hover:from-green-100 hover:to-emerald-100 transition-colors cursor-pointer py-3 md:py-4">
              <div className="flex justify-between items-center">
                <div className="flex items-center gap-3">
                  <Zap className="h-4 w-4 md:h-5 md:w-5 text-green-600" />
                  <div className="text-left">
                    <CardTitle className="text-base md:text-lg">预测模型</CardTitle>
                    <CardDescription className="text-xs md:text-sm">机器学习预测模型管理</CardDescription>
                  </div>
                </div>
                {expandedSections.predictions ? (
                  <ChevronDown className="h-4 w-4 md:h-5 md:w-5" />
                ) : (
                  <ChevronRight className="h-4 w-4 md:h-5 md:w-5" />
                )}
              </div>
            </CardHeader>
          </CollapsibleTrigger>
          <CollapsibleContent>
            <CardContent className="p-4">
              <div className="space-y-3">
                {aiData.predictiveModels.map((model, index) => (
                  <div key={index} className="bg-white border rounded-lg p-3 md:p-4">
                    <div className="flex flex-col md:flex-row md:items-center justify-between gap-3">
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-2">
                          <h3 className="font-medium text-sm md:text-base">{model.model}</h3>
                          <Badge className={getStatusColor(model.status)}>{model.status}</Badge>
                        </div>
                        <p className="text-xs md:text-sm text-gray-600 mb-2">{model.description}</p>
                        <div className="flex flex-wrap gap-4 text-xs">
                          <span>最后训练: {model.lastTrained}</span>
                          <span>预测数量: {model.predictions.toLocaleString()}</span>
                        </div>
                      </div>
                      <div className="text-right">
                        <div className="text-lg font-bold text-green-600">{model.accuracy}%</div>
                        <div className="text-xs text-gray-500">准确率</div>
                      </div>
                    </div>
                    <div className="mt-3">
                      <div className="flex justify-between text-xs mb-1">
                        <span>模型准确率</span>
                        <span>{model.accuracy}%</span>
                      </div>
                      <Progress value={model.accuracy} className="h-1.5" />
                    </div>
                  </div>
                ))}
              </div>
            </CardContent>
          </CollapsibleContent>
        </Card>
      </Collapsible>
    </div>
  )
}
