"use client"
import { useState } from "react"
import { Users, Database, Brain, BarChart3, Activity, MessageSquare, Zap, Send } from "lucide-react"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { useRouter } from "next/navigation"
import BottomTabs from "@/components/nav/bottom-tabs"

interface SystemStats {
  userCount: number
  userAssets: number
  dataVolume: string
  aiQueries: number
}

interface ChatMessage {
  id: string
  type: "user" | "ai"
  content: string
  timestamp: Date
}

export default function HomePage() {
  const router = useRouter()
  const [searchQuery, setSearchQuery] = useState("")
  const [selectedModel, setSelectedModel] = useState("gpt-5")
  const [showChat, setShowChat] = useState(false)
  const [chatMessages, setChatMessages] = useState<ChatMessage[]>([])
  const [isLoading, setIsLoading] = useState(false)

  const [stats, setStats] = useState<SystemStats>({
    userCount: 4000000000,
    userAssets: 4000000000,
    dataVolume: "2.5TB",
    aiQueries: 156789,
  })

  const handleAIChat = async () => {
    if (!searchQuery.trim()) return

    const userMessage: ChatMessage = {
      id: Date.now().toString(),
      type: "user",
      content: searchQuery,
      timestamp: new Date(),
    }

    setChatMessages((prev) => [...prev, userMessage])
    setIsLoading(true)
    setShowChat(true)

    // 模拟AI响应
    setTimeout(() => {
      const aiMessage: ChatMessage = {
        id: (Date.now() + 1).toString(),
        type: "ai",
        content: `基于${selectedModel}模型分析：${searchQuery}的相关数据显示用户增长趋势良好，建议进一步优化用户体验。`,
        timestamp: new Date(),
      }
      setChatMessages((prev) => [...prev, aiMessage])
      setIsLoading(false)
    }, 1500)

    setSearchQuery("")
  }

  // 格式化数字显示
  const formatNumber = (num: number): string => {
    if (num >= 1000000000) {
      return `${(num / 1000000000).toFixed(1)}B`
    }
    if (num >= 1000000) {
      return `${(num / 1000000).toFixed(1)}M`
    }
    if (num >= 1000) {
      return `${(num / 1000).toFixed(1)}K`
    }
    return num.toString()
  }

  // 大模型选项
  const modelOptions = [
    { value: "gpt-5", label: "GPT-5", provider: "OpenAI" },
    { value: "gpt-4", label: "GPT-4", provider: "OpenAI" },
    { value: "claude-3", label: "Claude-3", provider: "Anthropic" },
    { value: "gemini-pro", label: "Gemini Pro", provider: "Google" },
    { value: "qwen-max", label: "通义千问", provider: "阿里云" },
    { value: "baichuan", label: "百川大模型", provider: "百川智能" },
  ]

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-purple-50">
      <div className="container mx-auto px-4 py-6">
        {/* 页面标题 */}
        <div className="mb-6">
          <h1 className="text-3xl font-bold text-gray-900 mb-2">卡若数据资产中台</h1>
          <p className="text-gray-600">智能数据分析与AI助手平台</p>
        </div>

        {/* 核心统计数据 - 带图标的图表 */}
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
          <Card className="border-2 border-blue-200 bg-gradient-to-r from-blue-50 to-blue-100">
            <CardContent className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-gray-600 mb-1">用户总量</p>
                  <p className="text-2xl font-bold text-blue-600">{formatNumber(stats.userCount)}</p>
                </div>
                <div className="p-3 bg-blue-500 rounded-full">
                  <Users className="w-6 h-6 text-white" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card className="border-2 border-purple-200 bg-gradient-to-r from-purple-50 to-purple-100">
            <CardContent className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-gray-600 mb-1">用户资产</p>
                  <p className="text-2xl font-bold text-purple-600">{formatNumber(stats.userAssets)}</p>
                </div>
                <div className="p-3 bg-purple-500 rounded-full">
                  <BarChart3 className="w-6 h-6 text-white" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card className="border-2 border-green-200 bg-gradient-to-r from-green-50 to-green-100">
            <CardContent className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-gray-600 mb-1">数据容量</p>
                  <p className="text-2xl font-bold text-green-600">{stats.dataVolume}</p>
                </div>
                <div className="p-3 bg-green-500 rounded-full">
                  <Database className="w-6 h-6 text-white" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card className="border-2 border-orange-200 bg-gradient-to-r from-orange-50 to-orange-100">
            <CardContent className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-gray-600 mb-1">AI查询</p>
                  <p className="text-2xl font-bold text-orange-600">{formatNumber(stats.aiQueries)}</p>
                </div>
                <div className="p-3 bg-orange-500 rounded-full">
                  <Brain className="w-6 h-6 text-white" />
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* 整合AI对话与数据搜索功能 */}
        <Card className="mb-6 border-2 border-indigo-200 bg-gradient-to-r from-indigo-50 to-blue-50">
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <MessageSquare className="w-5 h-5 text-indigo-600" />
              AI智能助手
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            {/* 大模型选择 */}
            <div className="flex items-center gap-4">
              <span className="text-sm text-gray-600">选择大模型:</span>
              <Select value={selectedModel} onValueChange={setSelectedModel}>
                <SelectTrigger className="w-48">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {modelOptions.map((model) => (
                    <SelectItem key={model.value} value={model.value}>
                      <div className="flex items-center gap-2">
                        <Brain className="w-4 h-4" />
                        <span>{model.label}</span>
                        <Badge variant="secondary" className="text-xs">
                          {model.provider}
                        </Badge>
                      </div>
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            {/* 搜索输入框 */}
            <div className="relative">
              <MessageSquare className="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
              <Input
                placeholder="向AI提问，例如：分析用户增长趋势、搜索数据库信息..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                onKeyPress={(e) => e.key === "Enter" && handleAIChat()}
                className="pl-12 pr-24 h-12 text-base border-2 border-gray-200 focus:border-indigo-500 rounded-lg"
              />
              <Button
                onClick={handleAIChat}
                disabled={isLoading}
                className="absolute right-2 top-1/2 transform -translate-y-1/2 px-6 rounded-md"
              >
                <Send className="w-4 h-4 mr-2" />
                {isLoading ? "思考中..." : "提问"}
              </Button>
            </div>

            {showChat && chatMessages.length > 0 && (
              <div className="mt-4 p-4 bg-white rounded-lg border max-h-64 overflow-y-auto">
                <h4 className="font-medium mb-3 text-gray-700">对话记录</h4>
                <div className="space-y-3">
                  {chatMessages.map((message) => (
                    <div
                      key={message.id}
                      className={`flex ${message.type === "user" ? "justify-end" : "justify-start"}`}
                    >
                      <div
                        className={`max-w-xs lg:max-w-md px-4 py-2 rounded-lg ${
                          message.type === "user" ? "bg-indigo-500 text-white" : "bg-gray-100 text-gray-800"
                        }`}
                      >
                        <p className="text-sm">{message.content}</p>
                        <p className="text-xs opacity-70 mt-1">{message.timestamp.toLocaleTimeString()}</p>
                      </div>
                    </div>
                  ))}
                  {isLoading && (
                    <div className="flex justify-start">
                      <div className="bg-gray-100 text-gray-800 px-4 py-2 rounded-lg">
                        <p className="text-sm">AI正在思考...</p>
                      </div>
                    </div>
                  )}
                </div>
              </div>
            )}
          </CardContent>
        </Card>

        {/* 功能图表展示 */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <Card className="hover:shadow-md transition-shadow cursor-pointer" onClick={() => router.push("/user-pool")}>
            <CardContent className="p-6 text-center">
              <div className="p-4 bg-purple-100 rounded-full w-16 h-16 mx-auto mb-4 flex items-center justify-center">
                <Users className="w-8 h-8 text-purple-600" />
              </div>
              <h3 className="font-semibold mb-2">用户池</h3>
              <p className="text-sm text-gray-500">用户分群与标签管理</p>
              <div className="mt-4 flex justify-center">
                <Badge variant="secondary">
                  <Activity className="w-3 h-3 mr-1" />
                  实时更新
                </Badge>
              </div>
            </CardContent>
          </Card>

          <Card
            className="hover:shadow-md transition-shadow cursor-pointer"
            onClick={() => router.push("/data-platform")}
          >
            <CardContent className="p-6 text-center">
              <div className="p-4 bg-blue-100 rounded-full w-16 h-16 mx-auto mb-4 flex items-center justify-center">
                <Database className="w-8 h-8 text-blue-600" />
              </div>
              <h3 className="font-semibold mb-2">数据中台</h3>
              <p className="text-sm text-gray-500">数据源管理与AI模型</p>
              <div className="mt-4 flex justify-center">
                <Badge variant="secondary">
                  <Zap className="w-3 h-3 mr-1" />
                  高性能
                </Badge>
              </div>
            </CardContent>
          </Card>

          <Card
            className="hover:shadow-md transition-shadow cursor-pointer"
            onClick={() => router.push("/ai-assistant")}
          >
            <CardContent className="p-6 text-center">
              <div className="p-4 bg-green-100 rounded-full w-16 h-16 mx-auto mb-4 flex items-center justify-center">
                <Brain className="w-8 h-8 text-green-600" />
              </div>
              <h3 className="font-semibold mb-2">AI助手</h3>
              <p className="text-sm text-gray-500">智能问答与自动化</p>
              <div className="mt-4 flex justify-center">
                <Badge variant="secondary">
                  <MessageSquare className="w-3 h-3 mr-1" />
                  多模型
                </Badge>
              </div>
            </CardContent>
          </Card>
        </div>
      </div>
      {/* PC端隐藏底部导航栏 */}
      <div className="block md:hidden">
        <BottomTabs />
      </div>
    </div>
  )
}
