import {useEffect, useState} from 'react'
import {Link, useNavigate} from 'react-router-dom'
import Navbar from '../components/Navbar'
import {Bell, Heart, LogOut, MessageSquare, Settings, Shield, Star, User} from 'lucide-react'
import {authApi, type User as UserType} from '../api/auth'

export default function ProfilePage() {
  const [activeTab, setActiveTab] = useState<'overview' | 'settings' | 'favorites'>('overview')
  const [user, setUser] = useState<UserType | null>(null)
  const [loading, setLoading] = useState(true)
  const navigate = useNavigate()

  useEffect(() => {
    loadUserInfo()
  }, [])

  const loadUserInfo = async () => {
    try {
      const response = await authApi.getUserInfo()
      setUser(response.data)
    } catch (err) {
      console.error('获取用户信息失败:', err)
      navigate('/login')
    } finally {
      setLoading(false)
    }
  }

  const handleLogout = async () => {
    try {
      await authApi.logout()
    } catch (err) {
      console.error('登出失败:', err)
    } finally {
      localStorage.removeItem('token')
      localStorage.removeItem('refreshToken')
      localStorage.removeItem('user')
      navigate('/login')
    }
  }

  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 (!user) {
    return null
  }

  const recentChats = [
    { id: 1, character: '艾莉娅', lastMessage: '那么，准备好下一次冒险了吗？', time: '2分钟前' },
    { id: 2, character: '智者墨菲', lastMessage: '这个问题很有深度...', time: '1小时前' },
    { id: 3, character: '赛博朋克', lastMessage: '未来已来，你准备好了吗？', time: '3小时前' },
  ]

  const favoriteCharacters = [
    { id: 1, name: '艾莉娅', avatar: '🧝‍♀️', role: '冒险向导' },
    { id: 2, name: '智者墨菲', avatar: '🧙‍♂️', role: '知识导师' },
    { id: 3, name: '月影', avatar: '🥷', role: '神秘刺客' },
    { id: 4, name: '心理咨询师', avatar: '💝', role: '情感导师' },
  ]

  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-6xl mx-auto">
          <div className="glass rounded-3xl p-8 mb-6">
            <div className="flex flex-col md:flex-row items-center gap-6">
              <div className="w-24 h-24 bg-gradient-to-br from-primary to-secondary rounded-full flex items-center justify-center text-4xl">
                {user.avatar ? (
                  <img src={user.avatar} alt={user.nickName} className="w-full h-full rounded-full object-cover" />
                ) : (
                  '👤'
                )}
              </div>
              <div className="flex-1 text-center md:text-left">
                <h1 className="text-3xl font-bold mb-2">{user.nickName || user.username}</h1>
                <p className="text-white/60 mb-4">{user.email || '未设置邮箱'}</p>
                <div className="flex flex-wrap gap-6 justify-center md:justify-start">
                  <div>
                    <div className="text-2xl font-bold text-primary">{user.chatCount}</div>
                    <div className="text-sm text-white/60">总对话</div>
                  </div>
                  <div>
                    <div className="text-2xl font-bold text-secondary">{user.messageCount}</div>
                    <div className="text-sm text-white/60">消息数</div>
                  </div>
                  <div>
                    <div className="text-2xl font-bold text-cta">
                      {user.lastLoginAt ? new Date(user.lastLoginAt).toLocaleDateString() : '从未'}
                    </div>
                    <div className="text-sm text-white/60">最后登录</div>
                  </div>
                </div>
              </div>
              <button className="px-6 py-3 glass-hover rounded-xl cursor-pointer flex items-center gap-2">
                <Settings className="w-5 h-5" />
                编辑资料
              </button>
            </div>
          </div>

          <div className="glass rounded-2xl p-2 mb-6 inline-flex gap-2">
            <button
              onClick={() => setActiveTab('overview')}
              className={`px-6 py-2 rounded-lg text-sm cursor-pointer transition-all ${
                activeTab === 'overview' ? 'bg-gradient-to-r from-primary to-secondary' : 'hover:bg-white/5'
              }`}
            >
              概览
            </button>
            <button
              onClick={() => setActiveTab('favorites')}
              className={`px-6 py-2 rounded-lg text-sm cursor-pointer transition-all ${
                activeTab === 'favorites' ? 'bg-gradient-to-r from-primary to-secondary' : 'hover:bg-white/5'
              }`}
            >
              收藏
            </button>
            <button
              onClick={() => setActiveTab('settings')}
              className={`px-6 py-2 rounded-lg text-sm cursor-pointer transition-all ${
                activeTab === 'settings' ? 'bg-gradient-to-r from-primary to-secondary' : 'hover:bg-white/5'
              }`}
            >
              设置
            </button>
          </div>

          {activeTab === 'overview' && (
            <div className="grid md:grid-cols-2 gap-6">
              <div className="glass rounded-2xl p-6">
                <h2 className="text-xl font-semibold mb-4 flex items-center gap-2">
                  <MessageSquare className="w-5 h-5 text-primary" />
                  最近对话
                </h2>
                <div className="space-y-3">
                  {recentChats.map((chat) => (
                    <Link
                      key={chat.id}
                      to="/chat"
                      className="glass-hover rounded-xl p-4 block cursor-pointer"
                    >
                      <div className="flex items-center justify-between mb-2">
                        <span className="font-medium">{chat.character}</span>
                        <span className="text-xs text-white/40">{chat.time}</span>
                      </div>
                      <p className="text-sm text-white/60 truncate">{chat.lastMessage}</p>
                    </Link>
                  ))}
                </div>
              </div>

              <div className="glass rounded-2xl p-6">
                <h2 className="text-xl font-semibold mb-4 flex items-center gap-2">
                  <Star className="w-5 h-5 text-yellow-400" />
                  成就徽章
                </h2>
                <div className="grid grid-cols-3 gap-4">
                  {['🏆', '⭐', '🎯', '💎', '🔥', '👑'].map((badge, i) => (
                    <div key={i} className="glass-hover rounded-xl p-4 text-center cursor-pointer">
                      <div className="text-3xl mb-2">{badge}</div>
                      <div className="text-xs text-white/60">成就 {i + 1}</div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          )}

          {activeTab === 'favorites' && (
            <div className="glass rounded-2xl p-6">
              <h2 className="text-xl font-semibold mb-4 flex items-center gap-2">
                <Heart className="w-5 h-5 text-red-400" />
                收藏的角色
              </h2>
              <div className="grid md:grid-cols-4 gap-4">
                {favoriteCharacters.map((char) => (
                  <Link
                    key={char.id}
                    to={`/character/${char.id}`}
                    className="glass-hover rounded-xl p-6 text-center cursor-pointer"
                  >
                    <div className="text-5xl mb-3">{char.avatar}</div>
                    <h3 className="font-semibold mb-1">{char.name}</h3>
                    <p className="text-sm text-white/60">{char.role}</p>
                  </Link>
                ))}
              </div>
            </div>
          )}

          {activeTab === 'settings' && (
            <div className="space-y-6">
              <div className="glass rounded-2xl p-6">
                <h2 className="text-xl font-semibold mb-4 flex items-center gap-2">
                  <User className="w-5 h-5 text-primary" />
                  账号设置
                </h2>
                <div className="space-y-4">
                  <div>
                    <label className="text-sm text-white/80 mb-2 block">用户名</label>
                    <input
                      type="text"
                      defaultValue={user.username}
                      disabled
                      className="w-full px-4 py-3 glass rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/50 opacity-50"
                    />
                  </div>
                  <div>
                    <label className="text-sm text-white/80 mb-2 block">邮箱</label>
                    <input
                      type="email"
                      defaultValue={user.email}
                      className="w-full px-4 py-3 glass rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/50"
                    />
                  </div>
                  <div>
                    <label className="text-sm text-white/80 mb-2 block">昵称</label>
                    <input
                      type="text"
                      defaultValue={user.nickName}
                      className="w-full px-4 py-3 glass rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/50"
                    />
                  </div>
                </div>
              </div>

              <div className="glass rounded-2xl p-6">
                <h2 className="text-xl font-semibold mb-4 flex items-center gap-2">
                  <Shield className="w-5 h-5 text-secondary" />
                  隐私与安全
                </h2>
                <div className="space-y-3">
                  <label className="flex items-center justify-between cursor-pointer">
                    <span className="text-sm">公开我的收藏</span>
                    <input type="checkbox" defaultChecked className="cursor-pointer" />
                  </label>
                  <label className="flex items-center justify-between cursor-pointer">
                    <span className="text-sm">允许其他用户关注我</span>
                    <input type="checkbox" defaultChecked className="cursor-pointer" />
                  </label>
                  <label className="flex items-center justify-between cursor-pointer">
                    <span className="text-sm">显示在线状态</span>
                    <input type="checkbox" className="cursor-pointer" />
                  </label>
                </div>
              </div>

              <div className="glass rounded-2xl p-6">
                <h2 className="text-xl font-semibold mb-4 flex items-center gap-2">
                  <Bell className="w-5 h-5 text-cta" />
                  通知设置
                </h2>
                <div className="space-y-3">
                  <label className="flex items-center justify-between cursor-pointer">
                    <span className="text-sm">新消息通知</span>
                    <input type="checkbox" defaultChecked className="cursor-pointer" />
                  </label>
                  <label className="flex items-center justify-between cursor-pointer">
                    <span className="text-sm">新粉丝通知</span>
                    <input type="checkbox" defaultChecked className="cursor-pointer" />
                  </label>
                  <label className="flex items-center justify-between cursor-pointer">
                    <span className="text-sm">系统更新通知</span>
                    <input type="checkbox" className="cursor-pointer" />
                  </label>
                </div>
              </div>

              <div className="flex gap-3">
                <button className="px-6 py-3 bg-gradient-to-r from-primary to-secondary rounded-xl font-medium hover:opacity-90 transition-opacity cursor-pointer">
                  保存更改
                </button>
                <button
                  onClick={handleLogout}
                  className="px-6 py-3 glass-hover rounded-xl font-medium cursor-pointer flex items-center gap-2 text-red-400"
                >
                  <LogOut className="w-5 h-5" />
                  退出登录
                </button>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
