"use client"

import { useState } from "react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { PlusCircle, Search, Users, BarChart2, Edit, Trash2, ChevronDown, ChevronRight } from "lucide-react"
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"

interface UserSegment {
  id: string
  name: string
  description: string
  userCount: number
  criteria: string[]
  createdAt: Date
  updatedAt: Date
  status: "active" | "draft"
}

export function UserProfileSegments() {
  const [searchQuery, setSearchQuery] = useState("")
  const [openSections, setOpenSections] = useState({
    segmentList: true,
  })

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

  // 模拟数据
  const segments: UserSegment[] = [
    {
      id: "1",
      name: "高价值用户",
      description: "消费金额高且频次高的用户群体",
      userCount: 2450,
      criteria: ["消费金额>5000", "消费频次>10次/月", "活跃度>80%"],
      createdAt: new Date(2023, 5, 15),
      updatedAt: new Date(2023, 6, 20),
      status: "active",
    },
    {
      id: "2",
      name: "新注册用户",
      description: "最近30天内注册的新用户",
      userCount: 1254,
      criteria: ["注册时间<30天"],
      createdAt: new Date(2023, 4, 10),
      updatedAt: new Date(2023, 6, 18),
      status: "active",
    },
    {
      id: "3",
      name: "流失风险用户",
      description: "最近活跃度下降的用户",
      userCount: 876,
      criteria: ["最近登录>15天", "活跃度下降>50%"],
      createdAt: new Date(2023, 3, 5),
      updatedAt: new Date(2023, 5, 25),
      status: "active",
    },
    {
      id: "4",
      name: "企业客户",
      description: "企业类型的客户群体",
      userCount: 542,
      criteria: ["用户类型=企业", "员工数>50人"],
      createdAt: new Date(2023, 2, 20),
      updatedAt: new Date(2023, 6, 19),
      status: "active",
    },
    {
      id: "5",
      name: "潜在高转化用户",
      description: "浏览行为活跃但未转化的用户",
      userCount: 1320,
      criteria: ["浏览次数>20次/周", "未购买"],
      createdAt: new Date(2023, 1, 15),
      updatedAt: new Date(2023, 4, 10),
      status: "draft",
    },
  ]

  // 过滤分群
  const filteredSegments = segments.filter(
    (segment) =>
      segment.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      segment.description.toLowerCase().includes(searchQuery.toLowerCase()),
  )

  const formatDate = (date: Date) => {
    return date.toLocaleDateString("zh-CN", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
    })
  }

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <h2 className="text-xl font-semibold">用户分群管理</h2>
        <Button>
          <PlusCircle className="mr-2 h-4 w-4" />
          创建新分群
        </Button>
      </div>

      <Collapsible open={openSections.segmentList} onOpenChange={() => toggleSection("segmentList")}>
        <div className="border rounded-md p-4">
          <CollapsibleTrigger className="flex justify-between items-center w-full mb-4">
            <h3 className="text-lg font-medium">分群列表</h3>
            {openSections.segmentList ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
          </CollapsibleTrigger>
          <CollapsibleContent>
            <div className="flex justify-between items-center mb-4">
              <div className="flex space-x-2">
                <Select defaultValue="all">
                  <SelectTrigger className="w-[150px]">
                    <SelectValue placeholder="状态" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">全部状态</SelectItem>
                    <SelectItem value="active">已激活</SelectItem>
                    <SelectItem value="draft">草稿</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="relative w-64">
                <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
                <Input
                  placeholder="搜索分群..."
                  className="pl-8"
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                />
              </div>
            </div>

            <div className="rounded-md border">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>分群名称</TableHead>
                    <TableHead>描述</TableHead>
                    <TableHead>用户数量</TableHead>
                    <TableHead>筛选条件</TableHead>
                    <TableHead>创建时间</TableHead>
                    <TableHead>更新时间</TableHead>
                    <TableHead>状态</TableHead>
                    <TableHead className="text-right">操作</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {filteredSegments.map((segment) => (
                    <TableRow key={segment.id}>
                      <TableCell className="font-medium">{segment.name}</TableCell>
                      <TableCell>{segment.description}</TableCell>
                      <TableCell>
                        <div className="flex items-center">
                          <Users className="h-4 w-4 mr-1 text-muted-foreground" />
                          {segment.userCount.toLocaleString()}
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="flex flex-wrap gap-1">
                          {segment.criteria.map((criterion) => (
                            <Badge key={criterion} variant="outline" className="text-xs">
                              {criterion}
                            </Badge>
                          ))}
                        </div>
                      </TableCell>
                      <TableCell>{formatDate(segment.createdAt)}</TableCell>
                      <TableCell>{formatDate(segment.updatedAt)}</TableCell>
                      <TableCell>
                        <Badge variant={segment.status === "active" ? "default" : "secondary"}>
                          {segment.status === "active" ? "已激活" : "草稿"}
                        </Badge>
                      </TableCell>
                      <TableCell className="text-right">
                        <div className="flex justify-end space-x-2">
                          <Button variant="ghost" size="icon">
                            <Edit className="h-4 w-4" />
                          </Button>
                          <Button variant="ghost" size="icon">
                            <BarChart2 className="h-4 w-4" />
                          </Button>
                          <Button variant="ghost" size="icon" className="text-red-500">
                            <Trash2 className="h-4 w-4" />
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          </CollapsibleContent>
        </div>
      </Collapsible>
    </div>
  )
}
