import {useEffect, useState} from 'react'
import {Link, useNavigate} from 'react-router-dom'
import Navbar from '../components/Navbar'
import {Book, MessageSquare, Search, Star} from 'lucide-react'
import {type Character, characterApi} from '../api/character'

const categories = ['全部', '冒险', '知识', '娱乐', '情感', '科幻', '奇幻', '历史']

export default function CharacterMarket() {
  const [characters, setCharacters] = useState<Character[]>([])
  const [selectedCategory, setSelectedCategory] = useState('全部')
  const [searchQuery, setSearchQuery] = useState('')
  const [loading, setLoading] = useState(true)
  const [page, setPage] = useState(1)
  const [total, setTotal] = useState(0)
  const navigate = useNavigate()

  useEffect(() => {
    loadCharacters()
  }, [page, searchQuery, selectedCategory])

  const loadCharacters = async () => {
    try {
      setLoading(true)
      const response = await characterApi.getCharacterList({
        page,
        pageSize: 20,
        keyword: searchQuery || undefined,
        tag: selectedCategory !== '全部' ? selectedCategory : undefined,
        isPublic: true, // 只获取公开的角色卡
      })
      setCharacters(response.data.list)
      setTotal(response.data.total)
    } catch (err: any) {
      console.error('获取角色卡列表失败:', err)
      if (err.response?.status === 401) {
        navigate('/login')
      }
    } finally {
      setLoading(false)
    }
  }

  const getWorldBookCount = (character: Character) => {
    if (!character.characterBook) return 0
    try {
      const book = typeof character.characterBook === 'string'
        ? JSON.parse(character.characterBook)
        : character.characterBook
      return book.entries?.length || 0
    } catch {
      return 0
    }
  }

  if (loading && characters.length === 0) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-[#0A0A0F] via-[#1A0B2E] to-[#0A0A0F] flex items-center justify-center">
        <div className="text-white">加载中...</div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-[#0A0A0F] via-[#1A0B2E] to-[#0A0A0F]">
      <Navbar />

      <div className="pt-32 pb-20 px-4">
        <div className="max-w-7xl mx-auto">
          <div className="mb-8">
            <h1 className="text-4xl font-bold mb-2">角色广场</h1>
            <p className="text-white/60">探索并选择你喜欢的 AI 角色</p>
          </div>

          <div className="glass rounded-2xl p-6 mb-8">
            <div className="flex flex-col md:flex-row gap-4">
              <div className="flex-1 relative">
                <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-white/40" />
                <input
                  type="text"
                  placeholder="搜索角色名称或描述..."
                  value={searchQuery}
                  onChange={(e) => {
                    setSearchQuery(e.target.value)
                    setPage(1)
                  }}
                  className="w-full pl-12 pr-4 py-3 glass rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/50"
                />
              </div>
            </div>

            <div className="flex gap-2 mt-4 overflow-x-auto pb-2">
              {categories.map((cat) => (
                <button
                  key={cat}
                  onClick={() => {
                    setSelectedCategory(cat)
                    setPage(1)
                  }}
                  className={`px-4 py-2 rounded-lg text-sm whitespace-nowrap cursor-pointer transition-all ${
                    selectedCategory === cat
                      ? 'bg-gradient-to-r from-primary to-secondary'
                      : 'glass-hover'
                  }`}
                >
                  {cat}
                </button>
              ))}
            </div>
          </div>

          {characters.length === 0 ? (
            <div className="glass rounded-2xl p-12 text-center">
              <p className="text-white/60">暂无公开角色卡</p>
            </div>
          ) : (
            <>
              <div className="grid md:grid-cols-3 lg:grid-cols-4 gap-6">
                {characters.map((char) => {
                  const worldBookCount = getWorldBookCount(char)
                  return (
                    <Link
                      key={char.id}
                      to={`/character/${char.id}`}
                      className="glass-hover rounded-2xl overflow-hidden cursor-pointer group"
                    >
                      <div className="relative h-48 bg-gradient-to-br from-primary/20 to-secondary/20">
                        {char.avatar ? (
                          <img src={char.avatar} alt={char.name} className="w-full h-full object-cover" />
                        ) : (
                          <div className="w-full h-full flex items-center justify-center text-6xl">
                            👤
                          </div>
                        )}
                        <div className="absolute inset-0 bg-gradient-to-t from-[#0A0A0F] to-transparent" />
                        {worldBookCount > 0 && (
                          <div className="absolute top-3 right-3 px-2 py-1 glass rounded-lg flex items-center gap-1 text-xs">
                            <Book className="w-3 h-3" />
                            {worldBookCount}
                          </div>
                        )}
                      </div>

                      <div className="p-4">
                        <h3 className="text-lg font-semibold mb-1 group-hover:text-primary transition-colors truncate">
                          {char.name}
                        </h3>
                        <p className="text-sm text-white/60 mb-3">{char.creator || '未知作者'}</p>
                        <p className="text-xs text-white/40 mb-4 line-clamp-2">
                          {char.description || '暂无描述'}
                        </p>

                        {char.tags && char.tags.length > 0 && (
                          <div className="flex flex-wrap gap-1 mb-3">
                            {char.tags.slice(0, 2).map((tag, i) => (
                              <span key={i} className="text-xs px-2 py-1 bg-primary/20 text-primary rounded">
                                {tag}
                              </span>
                            ))}
                          </div>
                        )}

                        <div className="flex items-center justify-between text-xs text-white/40 pt-4 border-t border-white/10">
                          <div className="flex items-center gap-1">
                            <MessageSquare className="w-3 h-3" />
                            <span>{char.useCount}</span>
                          </div>
                          <div className="flex items-center gap-1">
                            <Star className="w-3 h-3" />
                            <span>{char.favoriteCount}</span>
                          </div>
                        </div>
                      </div>
                    </Link>
                  )
                })}
              </div>

              {total > 20 && (
                <div className="flex justify-center gap-2 mt-8">
                  <button
                    onClick={() => setPage(p => Math.max(1, p - 1))}
                    disabled={page === 1}
                    className="px-4 py-2 glass-hover rounded-lg cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    上一页
                  </button>
                  <span className="px-4 py-2 glass rounded-lg">
                    {page} / {Math.ceil(total / 20)}
                  </span>
                  <button
                    onClick={() => setPage(p => p + 1)}
                    disabled={page >= Math.ceil(total / 20)}
                    className="px-4 py-2 glass-hover rounded-lg cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    下一页
                  </button>
                </div>
              )}
            </>
          )}
        </div>
      </div>
    </div>
  )
}
