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

export default function CharacterDetail() {
  const { id } = useParams<{ id: string }>()
  const [character, setCharacter] = useState<Character | null>(null)
  const [loading, setLoading] = useState(true)
  const navigate = useNavigate()

  useEffect(() => {
    if (id) {
      loadCharacter(parseInt(id))
    }
  }, [id])

  const loadCharacter = async (characterId: number) => {
    try {
      setLoading(true)
      const response = await characterApi.getCharacterById(characterId)
      setCharacter(response.data)
    } catch (err: any) {
      console.error('获取角色卡详情失败:', err)
      alert('角色卡不存在或无权访问')
      navigate('/market')
    } finally {
      setLoading(false)
    }
  }

  const getWorldBookStats = () => {
    if (!character?.characterBook) return null
    try {
      const book = typeof character.characterBook === 'string'
        ? JSON.parse(character.characterBook)
        : character.characterBook
      return {
        name: book.name || '未命名世界书',
        entryCount: book.entries?.length || 0
      }
    } catch {
      return null
    }
  }

  const handleStartChat = () => {
    if (!character) return
    navigate(`/chat?character=${character.id}`)
  }

  if (loading) {
    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>
    )
  }

  if (!character) {
    return null
  }

  const worldBookStats = getWorldBookStats()

  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-5xl mx-auto">
          <Link
            to="/market"
            className="inline-flex items-center gap-2 text-white/60 hover:text-white transition-colors mb-6 cursor-pointer"
          >
            <ArrowLeft className="w-4 h-4" />
            返回角色广场
          </Link>

          <div className="glass rounded-3xl overflow-hidden mb-6">
            <div className="relative h-64 bg-gradient-to-br from-primary/20 to-secondary/20">
              {character.avatar ? (
                <img src={character.avatar} alt={character.name} className="w-full h-full object-cover" />
              ) : (
                <div className="w-full h-full flex items-center justify-center text-8xl">
                  👤
                </div>
              )}
              <div className="absolute inset-0 bg-gradient-to-t from-[#0A0A0F] to-transparent" />
            </div>

            <div className="p-8">
              <div className="flex flex-col md:flex-row gap-8">
                <div className="flex-1">
                  <div className="flex items-start justify-between mb-4">
                    <div>
                      <h1 className="text-3xl font-bold mb-2">{character.name}</h1>
                      <p className="text-lg text-white/60">{character.creator || '未知作者'}</p>
                    </div>
                    <div className="flex items-center gap-4 text-sm text-white/60">
                      <div className="flex items-center gap-1">
                        <MessageSquare className="w-4 h-4" />
                        <span>{character.useCount} 次使用</span>
                      </div>
                      <div className="flex items-center gap-1">
                        <Star className="w-4 h-4" />
                        <span>{character.favoriteCount} 收藏</span>
                      </div>
                    </div>
                  </div>

                  {character.tags && character.tags.length > 0 && (
                    <div className="flex flex-wrap gap-2 mb-4">
                      {character.tags.map((tag, i) => (
                        <span key={i} className="px-3 py-1 glass rounded-lg text-sm flex items-center gap-1">
                          <Tag className="w-3 h-3" />
                          {tag}
                        </span>
                      ))}
                    </div>
                  )}

                  <p className="text-white/80 leading-relaxed mb-6">
                    {character.description || '暂无描述'}
                  </p>

                  <div className="flex gap-3">
                    <button
                      onClick={handleStartChat}
                      className="flex-1 px-6 py-3 bg-gradient-to-r from-primary to-secondary rounded-xl font-medium hover:opacity-90 transition-opacity cursor-pointer flex items-center justify-center gap-2"
                    >
                      <Play className="w-5 h-5" />
                      开始对话
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div className="grid md:grid-cols-2 gap-6">
            {character.personality && (
              <div className="glass rounded-2xl p-6">
                <h2 className="text-xl font-semibold mb-4">性格特征</h2>
                <p className="text-white/80 whitespace-pre-wrap">{character.personality}</p>
              </div>
            )}

            {character.scenario && (
              <div className="glass rounded-2xl p-6">
                <h2 className="text-xl font-semibold mb-4">场景设定</h2>
                <p className="text-white/80 whitespace-pre-wrap">{character.scenario}</p>
              </div>
            )}

            {character.firstMes && (
              <div className="glass rounded-2xl p-6">
                <h2 className="text-xl font-semibold mb-4">第一条消息</h2>
                <div className="glass-hover rounded-xl p-4">
                  <p className="text-white/80 whitespace-pre-wrap">{character.firstMes}</p>
                </div>
              </div>
            )}

            {worldBookStats && worldBookStats.entryCount > 0 && (
              <div className="glass rounded-2xl p-6">
                <h2 className="text-xl font-semibold mb-4 flex items-center gap-2">
                  <Book className="w-5 h-5 text-secondary" />
                  世界书
                </h2>
                <div className="text-white/60">
                  <div>{worldBookStats.name}</div>
                  <div>{worldBookStats.entryCount} 个条目</div>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  )
}
