import { Link } from '@tanstack/react-router'
import { useAuthStore } from '@/store/auth-store'
import { useAuthModalStore } from '@/store/auth-modal-store'
import { useGamification, useLeaderboard } from '@/hooks/use-gamification'
import { XP_REWARDS } from '@/lib/gamification-service'
import { StatsRow } from './StatsRow'
import { XpProgressCard } from './XpProgressCard'
import { WeeklySection } from './WeeklySection'
import { XuEconomyCard } from './XuEconomyCard'
import { LeaderboardCard } from './LeaderboardCard'

// Numeric level from XP (1 per 100 XP, min 1)
export function calcNumericLevel(xp: number) {
  return Math.max(1, Math.floor(xp / 100))
}

// XP needed for next numeric level
export function calcXpNextLevel(xp: number) {
  return (Math.floor(xp / 100) + 1) * 100
}

export function Dashboard() {
  const user = useAuthStore((s) => s.user)
  const openModal = useAuthModalStore((s) => s.open)
  const { data: gam, isLoading } = useGamification()
  const { data: leaderboard } = useLeaderboard()

  if (!user) {
    return (
      <div className="px-4 lg:px-6 py-12 max-w-6xl mx-auto flex flex-col items-center text-center gap-4">
        <span className="material-symbols-outlined text-slate-300" style={{ fontSize: 64 }}>emoji_events</span>
        <h1 className="text-xl font-bold text-slate-700">Bảng thành tích</h1>
        <p className="text-slate-400 text-sm max-w-xs">
          Đăng nhập để xem streak, XP, Xu và bảng xếp hạng của bạn.
        </p>
        <button
          onClick={() => openModal('login')}
          className="mt-2 px-6 py-2.5 bg-blue-600 text-white rounded-full font-bold text-sm hover:bg-blue-700 transition-colors"
        >
          Đăng nhập
        </button>
      </div>
    )
  }

  // Derive weekly completed from leaderboard XP
  const userLbRow = leaderboard?.find((r) => r.userId === user.id)
  const weeklyXp = userLbRow?.xpEarned ?? 0
  const weeklyCompleted = Math.min(Math.floor(weeklyXp / XP_REWARDS.test), 5)

  const xu = gam?.xu ?? 50
  const streak = gam?.streak ?? 0
  const xp = gam?.xp ?? 0
  const level = gam?.level ?? 'beginner'
  const lastActive = gam?.lastActive ?? null

  return (
    <div className="px-4 lg:px-6 py-6 max-w-6xl mx-auto">
      <div className="mb-6">
        <h1 className="text-2xl font-extrabold text-slate-800 mb-1">Bảng thành tích</h1>
        <p className="text-slate-400 text-sm">
          Xin chào, <span className="font-semibold text-slate-600">{user.name}</span> — tiếp tục chuỗi học tập nhé!
        </p>
      </div>

      {isLoading ? (
        <div className="grid grid-cols-1 md:grid-cols-3 gap-5 mb-6">
          {[1, 2, 3].map((i) => (
            <div key={i} className="bg-white rounded-xl p-6 shadow-sm h-32 animate-pulse bg-slate-100" />
          ))}
        </div>
      ) : (
        <StatsRow xu={xu} streak={streak} xp={xp} level={level} />
      )}

      <div className="grid grid-cols-1 lg:grid-cols-12 gap-5 mb-5">
        <XpProgressCard xp={xp} />
        <WeeklySection streak={streak} lastActive={lastActive} weeklyCompleted={weeklyCompleted} />
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-12 gap-5">
        <XuEconomyCard />
        <LeaderboardCard />
      </div>

      <Link
        to="/toeic"
        className="fixed bottom-24 right-6 lg:bottom-8 lg:right-8 w-14 h-14 bg-blue-600 text-white rounded-2xl flex items-center justify-center shadow-2xl hover:scale-110 active:scale-95 transition-all z-40"
        title="Học ngay"
      >
        <span className="material-symbols-outlined text-2xl">play_arrow</span>
      </Link>
    </div>
  )
}
