"use client"

import { useState, useEffect } from "react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Avatar } from "@/components/ui/avatar"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import {
  Search,
  Filter,
  SortAsc,
  User,
  Tag,
  Database,
  BrainCircuit,
  Phone,
  Mail,
  MapPin,
  Calendar,
  TrendingUp,
  Eye,
  RefreshCw,
} from "lucide-react"

export default function SearchPage() {
  const [searchQuery, setSearchQuery] = useState("")
  const [searchType, setSearchType] = useState("all")
  const [sortBy, setSortBy] = useState("relevance")
  const [isSearching, setIsSearching] = useState(false)
  const [searchResults, setSearchResults] = useState<any[]>([])

  // 模拟搜索数据
  const mockSearchData = [
    {
      id: "user_001",
      type: "user",
      name: "张明华",
      phone: "13800138000",
      email: "zhangsan@example.com",
      company: "科技创新有限公司",
      tags: ["高价值", "技术决策者", "活跃用户", "iOS用户"],
      aiInsights: ["科技爱好者", "决策影响者", "高消费潜力"],
      lastActive: "2小时前",
      location: "北京市",
      avatar: "/placeholder.svg?height=40&width=40",
      rfmScore: 95,
      sources: ["抖音", "微信", "表单提交"],
      joinDate: "2023-06-15",
      relevanceScore: 98,
    },
    {
      id: "user_002",
      type: "user",
      name: "李雨婷",
      phone: "13900139001",
      email: "lisi@example.com",
      company: "数字营销公司",
      tags: ["中高价值", "产品经理", "内容创作者"],
      aiInsights: ["创意思维", "社交活跃", "品牌敏感"],
      lastActive: "1天前",
      location: "上海市",
      avatar: "/placeholder.svg?height=40&width=40",
      rfmScore: 78,
      sources: ["小红书", "微信", "客服咨询"],
      joinDate: "2023-08-22",
      relevanceScore: 85,
    },
    {
      id: "tag_001",
      type: "tag",
      name: "高价值用户",
      description: "RFM评分超过80分的用户",
      userCount: 12456,
      category: "价值分类",
      createdDate: "2023-05-10",
      relevanceScore: 92,
    },
    {
      id: "insight_001",
      type: "insight",
      title: "用户行为模式分析",
      description: "基于AI分析的用户行为偏好洞察",
      confidence: 94.5,
      affectedUsers: 8765,
      createdDate: "2023-12-01",
      relevanceScore: 88,
    },
  ]

  // 搜索处理
  const handleSearch = async (query: string) => {
    if (!query.trim()) {
      setSearchResults([])
      return
    }

    setIsSearching(true)

    // 模拟搜索延迟
    setTimeout(() => {
      const filtered = mockSearchData.filter((item) => {
        const searchText = query.toLowerCase()

        if (searchType !== "all" && item.type !== searchType) {
          return false
        }

        // 根据不同类型进行搜索
        switch (item.type) {
          case "user":
            return (
              item.name.toLowerCase().includes(searchText) ||
              item.phone.includes(searchText) ||
              item.email.toLowerCase().includes(searchText) ||
              item.company.toLowerCase().includes(searchText) ||
              item.tags.some((tag: string) => tag.toLowerCase().includes(searchText)) ||
              item.aiInsights.some((insight: string) => insight.toLowerCase().includes(searchText)) ||
              item.location.toLowerCase().includes(searchText)
            )
          case "tag":
            return (
              item.name.toLowerCase().includes(searchText) ||
              item.description.toLowerCase().includes(searchText) ||
              item.category.toLowerCase().includes(searchText)
            )
          case "insight":
            return item.title.toLowerCase().includes(searchText) || item.description.toLowerCase().includes(searchText)
          default:
            return false
        }
      })

      // 排序
      if (sortBy === "relevance") {
        filtered.sort((a, b) => b.relevanceScore - a.relevanceScore)
      } else if (sortBy === "date") {
        filtered.sort(
          (a, b) => new Date(b.createdDate || b.joinDate).getTime() - new Date(a.createdDate || a.joinDate).getTime(),
        )
      } else if (sortBy === "name") {
        filtered.sort((a, b) => (a.name || a.title).localeCompare(b.name || b.title))
      }

      setSearchResults(filtered)
      setIsSearching(false)
    }, 800)
  }

  // 搜索输入处理
  useEffect(() => {
    const timeoutId = setTimeout(() => {
      if (searchQuery) {
        handleSearch(searchQuery)
      }
    }, 500)

    return () => clearTimeout(timeoutId)
  }, [searchQuery, searchType, sortBy])

  const getTypeIcon = (type: string) => {
    switch (type) {
      case "user":
        return <User className="h-4 w-4 text-blue-500" />
      case "tag":
        return <Tag className="h-4 w-4 text-green-500" />
      case "insight":
        return <BrainCircuit className="h-4 w-4 text-purple-500" />
      default:
        return <Database className="h-4 w-4 text-gray-500" />
    }
  }

  const getTypeBadgeColor = (type: string) => {
    switch (type) {
      case "user":
        return "bg-blue-100 text-blue-700"
      case "tag":
        return "bg-green-100 text-green-700"
      case "insight":
        return "bg-purple-100 text-purple-700"
      default:
        return "bg-gray-100 text-gray-700"
    }
  }

  return (
    <div className="container mx-auto py-6 space-y-6">
      {/* 页面标题 */}
      <div className="flex flex-col md:flex-row md:justify-between md:items-center gap-4">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">智能搜索</h1>
          <p className="text-muted-foreground">AI驱动的全局智能搜索引擎</p>
        </div>
      </div>

      {/* 搜索栏 */}
      <Card className="bg-gradient-to-r from-purple-50 to-blue-50 border-none shadow-lg">
        <CardContent className="p-6">
          <div className="space-y-4">
            {/* 主搜索框 */}
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-muted-foreground" />
              <Input
                type="text"
                placeholder="搜索用户、标签、洞察或任何相关信息..."
                className="pl-10 h-12 text-base border-2 border-purple-200 focus:border-purple-400"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
              />
              {isSearching && (
                <div className="absolute right-3 top-1/2 transform -translate-y-1/2">
                  <RefreshCw className="h-5 w-5 animate-spin text-purple-500" />
                </div>
              )}
            </div>

            {/* 搜索选项 */}
            <div className="flex flex-wrap gap-4">
              <div className="flex items-center gap-2">
                <Filter className="h-4 w-4 text-muted-foreground" />
                <Select value={searchType} onValueChange={setSearchType}>
                  <SelectTrigger className="w-[120px]">
                    <SelectValue placeholder="类型" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">全部</SelectItem>
                    <SelectItem value="user">用户</SelectItem>
                    <SelectItem value="tag">标签</SelectItem>
                    <SelectItem value="insight">洞察</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div className="flex items-center gap-2">
                <SortAsc className="h-4 w-4 text-muted-foreground" />
                <Select value={sortBy} onValueChange={setSortBy}>
                  <SelectTrigger className="w-[120px]">
                    <SelectValue placeholder="排序" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="relevance">相关性</SelectItem>
                    <SelectItem value="date">时间</SelectItem>
                    <SelectItem value="name">名称</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* 搜索结果 */}
      {searchQuery && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center justify-between">
              <span>搜索结果</span>
              <Badge variant="outline">{searchResults.length} 个结果</Badge>
            </CardTitle>
            <CardDescription>
              搜索关键词: "{searchQuery}"{searchType !== "all" && ` · 类型: ${searchType}`}
            </CardDescription>
          </CardHeader>
          <CardContent>
            {searchResults.length > 0 ? (
              <div className="space-y-4">
                {searchResults.map((result) => (
                  <div
                    key={result.id}
                    className="flex items-start gap-4 p-4 border rounded-lg hover:bg-gray-50 transition-colors cursor-pointer"
                  >
                    {/* 类型图标 */}
                    <div className="flex-shrink-0 mt-1">
                      {result.type === "user" ? (
                        <Avatar className="h-10 w-10">
                          <img src={result.avatar || "/placeholder.svg"} alt={result.name} />
                        </Avatar>
                      ) : (
                        <div className="w-10 h-10 rounded-full bg-gray-100 flex items-center justify-center">
                          {getTypeIcon(result.type)}
                        </div>
                      )}
                    </div>

                    {/* 内容 */}
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 mb-2">
                        <h3 className="font-semibold text-lg truncate">{result.name || result.title}</h3>
                        <Badge className={getTypeBadgeColor(result.type)}>
                          {result.type === "user" ? "用户" : result.type === "tag" ? "标签" : "洞察"}
                        </Badge>
                        {result.relevanceScore && (
                          <Badge variant="outline" className="text-xs">
                            相关性: {result.relevanceScore}%
                          </Badge>
                        )}
                      </div>

                      {/* 用户信息 */}
                      {result.type === "user" && (
                        <div className="space-y-2">
                          <div className="flex items-center gap-4 text-sm text-muted-foreground">
                            <span className="flex items-center gap-1">
                              <Phone className="h-3 w-3" />
                              {result.phone}
                            </span>
                            <span className="flex items-center gap-1">
                              <Mail className="h-3 w-3" />
                              {result.email}
                            </span>
                            <span className="flex items-center gap-1">
                              <MapPin className="h-3 w-3" />
                              {result.location}
                            </span>
                          </div>
                          <div className="flex items-center gap-2">
                            <span className="text-sm text-muted-foreground">公司:</span>
                            <span className="text-sm">{result.company}</span>
                            <Badge className="bg-orange-100 text-orange-700 text-xs">RFM: {result.rfmScore}</Badge>
                          </div>
                          <div className="flex flex-wrap gap-1">
                            {result.aiInsights.slice(0, 3).map((insight: string, index: number) => (
                              <Badge key={index} className="text-xs bg-purple-100 text-purple-700">
                                {insight}
                              </Badge>
                            ))}
                          </div>
                        </div>
                      )}

                      {/* 标签信息 */}
                      {result.type === "tag" && (
                        <div className="space-y-2">
                          <p className="text-sm text-muted-foreground">{result.description}</p>
                          <div className="flex items-center gap-4 text-sm">
                            <span className="flex items-center gap-1">
                              <User className="h-3 w-3" />
                              {result.userCount.toLocaleString()} 用户
                            </span>
                            <span className="flex items-center gap-1">
                              <Tag className="h-3 w-3" />
                              {result.category}
                            </span>
                            <span className="flex items-center gap-1">
                              <Calendar className="h-3 w-3" />
                              {result.createdDate}
                            </span>
                          </div>
                        </div>
                      )}

                      {/* 洞察信息 */}
                      {result.type === "insight" && (
                        <div className="space-y-2">
                          <p className="text-sm text-muted-foreground">{result.description}</p>
                          <div className="flex items-center gap-4 text-sm">
                            <span className="flex items-center gap-1">
                              <TrendingUp className="h-3 w-3" />
                              置信度: {result.confidence}%
                            </span>
                            <span className="flex items-center gap-1">
                              <User className="h-3 w-3" />
                              影响用户: {result.affectedUsers.toLocaleString()}
                            </span>
                            <span className="flex items-center gap-1">
                              <Calendar className="h-3 w-3" />
                              {result.createdDate}
                            </span>
                          </div>
                        </div>
                      )}
                    </div>

                    {/* 操作按钮 */}
                    <div className="flex-shrink-0">
                      <Button variant="outline" size="sm">
                        <Eye className="h-4 w-4 mr-1" />
                        查看
                      </Button>
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <div className="text-center py-12">
                <Search className="h-12 w-12 mx-auto mb-4 text-muted-foreground opacity-50" />
                <h3 className="text-lg font-medium mb-2">未找到相关结果</h3>
                <p className="text-muted-foreground">尝试使用其他关键词或调整搜索条件</p>
              </div>
            )}
          </CardContent>
        </Card>
      )}

      {/* 搜索建议 */}
      {!searchQuery && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <BrainCircuit className="h-5 w-5 text-purple-600" />
              搜索建议
            </CardTitle>
            <CardDescription>热门搜索和智能推荐</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <h4 className="font-medium mb-3">热门搜索</h4>
                <div className="flex flex-wrap gap-2">
                  {["高价值用户", "技术决策者", "活跃用户", "流失风险", "新用户"].map((term) => (
                    <Button
                      key={term}
                      variant="outline"
                      size="sm"
                      onClick={() => setSearchQuery(term)}
                      className="text-xs"
                    >
                      {term}
                    </Button>
                  ))}
                </div>
              </div>
              <div>
                <h4 className="font-medium mb-3">智能推荐</h4>
                <div className="space-y-2">
                  <div className="text-sm text-muted-foreground">• 搜索特定用户: 输入姓名、手机号或邮箱</div>
                  <div className="text-sm text-muted-foreground">• 查找标签: 输入标签名称或描述</div>
                  <div className="text-sm text-muted-foreground">• 发现洞察: 输入行为模式或分析结果</div>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  )
}
