"use client"

import { useState, useMemo } from "react"
import { Card } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { 
  Breadcrumb, 
  BreadcrumbItem, 
  BreadcrumbLink, 
  BreadcrumbList, 
  BreadcrumbPage, 
  BreadcrumbSeparator 
} from "@/components/ui/breadcrumb"
import { 
  Search, 
  Tag, 
  TrendingUp, 
  Hash,
  ArrowRight,
  Camera,
  Sparkles
} from "lucide-react"
import { Photo } from "@/lib/queries"

interface TagCloudProps {
  photos: Photo[]
  onTagSelect: (tag: string) => void
  onPhotosView: () => void
}

interface TagStats {
  name: string
  count: number
  percentage: number
  recentPhotos: Photo[]
  categories: string[]
}

export function TagCloud({ photos, onTagSelect, onPhotosView }: TagCloudProps) {
  const [searchQuery, setSearchQuery] = useState("")
  const [sortBy, setSortBy] = useState<'popularity' | 'alphabetical' | 'recent'>('popularity')
  const [minCount, setMinCount] = useState(1)

  // 计算标签统计
  const tagStats = useMemo(() => {
    const stats = new Map<string, TagStats>()
    
    // 为没有标签的照片添加默认标签
    const allTags = photos.flatMap(photo => 
      photo.tags.length > 0 ? photo.tags : ['未分类']
    )
    
    // 统计每个标签
    allTags.forEach(tag => {
      if (!stats.has(tag)) {
        stats.set(tag, {
          name: tag,
          count: 0,
          percentage: 0,
          recentPhotos: [],
          categories: []
        })
      }
    })

    // 计算详细统计
    photos.forEach(photo => {
      const photoTags = photo.tags.length > 0 ? photo.tags : ['未分类']
      
      photoTags.forEach(tag => {
        const tagStat = stats.get(tag)!
        tagStat.count++
        tagStat.recentPhotos.push(photo)
        
        // 收集分类
        if (!tagStat.categories.includes(photo.category)) {
          tagStat.categories.push(photo.category)
        }
      })
    })

    // 计算百分比和排序最近照片
    const totalPhotos = photos.length
    stats.forEach(stat => {
      stat.percentage = (stat.count / totalPhotos) * 100
      stat.recentPhotos.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime())
      stat.recentPhotos = stat.recentPhotos.slice(0, 4) // 只保留最近4张
    })

    return Array.from(stats.values())
  }, [photos])

  // 过滤和排序标签
  const filteredTags = useMemo(() => {
    const filtered = tagStats.filter(tag => 
      tag.count >= minCount &&
      (searchQuery.trim() === '' || tag.name.toLowerCase().includes(searchQuery.toLowerCase()))
    )

    // 排序
    switch (sortBy) {
      case 'popularity':
        filtered.sort((a, b) => b.count - a.count)
        break
      case 'alphabetical':
        filtered.sort((a, b) => a.name.localeCompare(b.name))
        break
      case 'recent':
        filtered.sort((a, b) => {
          const aLatest = a.recentPhotos[0]?.date || ''
          const bLatest = b.recentPhotos[0]?.date || ''
          return bLatest.localeCompare(aLatest)
        })
        break
    }

    return filtered
  }, [tagStats, searchQuery, sortBy, minCount])

  // 获取标签字体大小（基于热度）
  const getTagSize = (percentage: number) => {
    if (percentage >= 20) return 'text-3xl'
    if (percentage >= 15) return 'text-2xl'
    if (percentage >= 10) return 'text-xl'
    if (percentage >= 5) return 'text-lg'
    return 'text-base'
  }

  // 获取标签颜色
  const getTagColor = (count: number, maxCount: number) => {
    const intensity = count / maxCount
    if (intensity >= 0.8) return 'bg-red-500 hover:bg-red-600'
    if (intensity >= 0.6) return 'bg-orange-500 hover:bg-orange-600'
    if (intensity >= 0.4) return 'bg-yellow-500 hover:bg-yellow-600'
    if (intensity >= 0.2) return 'bg-green-500 hover:bg-green-600'
    return 'bg-blue-500 hover:bg-blue-600'
  }

  const maxCount = Math.max(...tagStats.map(t => t.count))
  const totalTags = tagStats.length
  const totalUniqueCategories = new Set(photos.map(p => p.category)).size

  return (
    <div className="space-y-8">
      {/* 面包屑导航 */}
      <Breadcrumb>
        <BreadcrumbList>
          <BreadcrumbItem>
            <BreadcrumbLink onClick={onPhotosView} className="cursor-pointer">
              摄影作品
            </BreadcrumbLink>
          </BreadcrumbItem>
          <BreadcrumbSeparator />
          <BreadcrumbItem>
            <BreadcrumbPage>标签云</BreadcrumbPage>
          </BreadcrumbItem>
        </BreadcrumbList>
      </Breadcrumb>

      {/* 页面标题和统计 */}
      <div className="text-center">
        <h1 className="text-4xl font-light text-gray-900 mb-4">标签云</h1>
        <p className="text-lg text-gray-600 mb-6">
          通过 {totalTags} 个标签探索 {photos.length} 张照片
        </p>
        
        {/* 统计卡片 */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-8">
          <Card className="p-4">
            <div className="flex items-center gap-3">
              <div className="p-2 bg-blue-100 rounded-lg">
                <Tag className="h-5 w-5 text-blue-600" />
              </div>
              <div>
                <p className="text-2xl font-bold text-gray-900">{totalTags}</p>
                <p className="text-sm text-gray-600">标签总数</p>
              </div>
            </div>
          </Card>
          
          <Card className="p-4">
            <div className="flex items-center gap-3">
              <div className="p-2 bg-green-100 rounded-lg">
                <TrendingUp className="h-5 w-5 text-green-600" />
              </div>
              <div>
                <p className="text-2xl font-bold text-gray-900">{maxCount}</p>
                <p className="text-sm text-gray-600">最热标签</p>
              </div>
            </div>
          </Card>
          
          <Card className="p-4">
            <div className="flex items-center gap-3">
              <div className="p-2 bg-purple-100 rounded-lg">
                <Hash className="h-5 w-5 text-purple-600" />
              </div>
              <div>
                <p className="text-2xl font-bold text-gray-900">{totalUniqueCategories}</p>
                <p className="text-sm text-gray-600">涉及分类</p>
              </div>
            </div>
          </Card>
          
          <Card className="p-4">
            <div className="flex items-center gap-3">
              <div className="p-2 bg-yellow-100 rounded-lg">
                <Sparkles className="h-5 w-5 text-yellow-600" />
              </div>
              <div>
                <p className="text-2xl font-bold text-gray-900">
                  {totalTags > 0 ? Math.round(photos.length / totalTags) : 0}
                </p>
                <p className="text-sm text-gray-600">平均每标签</p>
              </div>
            </div>
          </Card>
        </div>
      </div>

      {/* 搜索和过滤控制 */}
      <div className="flex flex-col sm:flex-row gap-4 items-center justify-between">
        <div className="relative flex-1 max-w-md">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-4 w-4" />
          <Input
            type="text"
            placeholder="搜索标签..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="pl-10"
          />
        </div>
        
        <div className="flex items-center gap-2">
          <select 
            value={sortBy}
            onChange={(e) => setSortBy(e.target.value as 'popularity' | 'alphabetical' | 'recent')}
            className="px-3 py-2 border border-gray-300 rounded-md text-sm"
          >
            <option value="popularity">按热度</option>
            <option value="alphabetical">按字母</option>
            <option value="recent">按最近</option>
          </select>
          
          <select 
            value={minCount}
            onChange={(e) => setMinCount(parseInt(e.target.value))}
            className="px-3 py-2 border border-gray-300 rounded-md text-sm"
          >
            <option value={1}>显示全部</option>
            <option value={2}>至少2张</option>
            <option value={5}>至少5张</option>
            <option value={10}>至少10张</option>
          </select>
        </div>
      </div>

      {/* 标签云 - 文字云样式 */}
      <Card className="p-8">
        <div className="flex flex-wrap gap-4 justify-center items-center">
          {filteredTags.map((tag) => (
            <Button
              key={tag.name}
              variant="outline"
              onClick={() => onTagSelect(tag.name)}
              className={`
                ${getTagSize(tag.percentage)}
                ${getTagColor(tag.count, maxCount)}
                text-white border-0
                hover:scale-110 transition-all duration-200
                px-4 py-2 rounded-full
                font-medium
                shadow-md hover:shadow-lg
              `}
              style={{
                opacity: 0.8 + (tag.count / maxCount) * 0.2
              }}
            >
              {tag.name}
              <Badge variant="secondary" className="ml-2 bg-white/20 text-white">
                {tag.count}
              </Badge>
            </Button>
          ))}
        </div>
      </Card>

      {/* 详细标签列表 */}
      <div className="space-y-4">
        <h2 className="text-2xl font-semibold text-gray-900">标签详情</h2>
        
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {filteredTags.slice(0, 12).map((tag) => (
            <Card 
              key={tag.name}
              className="p-4 hover:shadow-lg transition-shadow cursor-pointer"
              onClick={() => onTagSelect(tag.name)}
            >
              <div className="flex items-center justify-between mb-3">
                <div className="flex items-center gap-2">
                  <Hash className="h-4 w-4 text-gray-500" />
                  <h3 className="font-medium text-gray-900">{tag.name}</h3>
                </div>
                <Badge variant="secondary">
                  {tag.count} 张
                </Badge>
              </div>
              
              <div className="space-y-2">
                <div className="flex items-center justify-between text-sm text-gray-600">
                  <span>占比 {tag.percentage.toFixed(1)}%</span>
                  <span>{tag.categories.length} 个分类</span>
                </div>
                
                <div className="w-full bg-gray-200 rounded-full h-2">
                  <div 
                    className={`h-2 rounded-full ${getTagColor(tag.count, maxCount)}`}
                    style={{ width: `${tag.percentage}%` }}
                  />
                </div>
                
                {/* 最近照片预览 */}
                <div className="flex -space-x-2 mt-3">
                  {tag.recentPhotos.slice(0, 3).map((photo, _idx) => (
                    <div 
                      key={photo.id}
                      className="w-8 h-8 rounded-full border-2 border-white overflow-hidden"
                    >
                      <img 
                        src={photo.src} 
                        alt={photo.title}
                        className="w-full h-full object-cover"
                      />
                    </div>
                  ))}
                  {tag.recentPhotos.length > 3 && (
                    <div className="w-8 h-8 rounded-full border-2 border-white bg-gray-100 flex items-center justify-center">
                      <span className="text-xs text-gray-600">+{tag.recentPhotos.length - 3}</span>
                    </div>
                  )}
                </div>
              </div>
              
              <div className="flex items-center justify-between mt-4 pt-3 border-t">
                <div className="flex items-center gap-1 text-sm text-gray-500">
                  <Camera className="h-3 w-3" />
                  <span>点击查看</span>
                </div>
                <ArrowRight className="h-4 w-4 text-gray-400" />
              </div>
            </Card>
          ))}
        </div>
      </div>

      {/* 空状态 */}
      {filteredTags.length === 0 && (
        <div className="text-center py-12">
          <Tag className="h-12 w-12 text-gray-400 mx-auto mb-4" />
          <h3 className="text-lg font-medium text-gray-900 mb-2">
            {searchQuery ? '未找到匹配的标签' : '暂无标签'}
          </h3>
          <p className="text-gray-600 mb-6">
            {searchQuery ? '尝试使用不同的关键词搜索' : '开始为照片添加标签'}
          </p>
          {searchQuery && (
            <Button
              variant="outline"
              onClick={() => setSearchQuery("")}
            >
              清除搜索
            </Button>
          )}
        </div>
      )}
    </div>
  )
}