import { cn } from '@/lib/utils'
import { useAuthStore } from '@/store/auth-store'
import { useLeaderboard } from '@/hooks/use-gamification'

function RankBadge({ rank }: { rank: number }) {
  return (
    <div className={cn(
      'w-8 h-8 flex items-center justify-center font-bold rounded-full text-xs',
      rank === 1 ? 'bg-amber-200 text-amber-800' :
      rank === 2 ? 'bg-slate-200 text-slate-700' :
      rank === 3 ? 'bg-orange-200 text-orange-700' :
      'bg-slate-100 text-slate-600',
    )}>
      {rank}
    </div>
  )
}

function initials(name: string) {
  return name.split(' ').map((w) => w[0]).slice(-2).join('').toUpperCase()
}

export function LeaderboardCard() {
  const user = useAuthStore((s) => s.user)
  const { data: rows, isLoading } = useLeaderboard()

  return (
    <div className="lg:col-span-8 bg-white p-6 rounded-xl shadow-sm">
      <div className="flex items-center justify-between mb-5">
        <h3 className="text-base font-bold text-slate-800">Bảng xếp hạng tuần</h3>
        <span className="px-3 py-1 bg-blue-600 text-white rounded-full text-xs font-bold">Top tuần này</span>
      </div>

      {isLoading && (
        <div className="space-y-2">
          {[1, 2, 3].map((i) => (
            <div key={i} className="h-12 bg-slate-100 rounded-xl animate-pulse" />
          ))}
        </div>
      )}

      {!isLoading && (!rows || rows.length === 0) && (
        <div className="text-center py-8 text-slate-400 text-sm">
          <span className="material-symbols-outlined block mb-2 text-slate-300" style={{ fontSize: 40 }}>leaderboard</span>
          Chưa có dữ liệu tuần này. Hãy hoàn thành bài học để xuất hiện trên bảng!
        </div>
      )}

      {!isLoading && rows && rows.length > 0 && (
        <table className="w-full text-left border-separate border-spacing-y-1.5">
          <thead>
            <tr className="text-[10px] font-bold uppercase tracking-widest text-slate-400">
              <th className="pb-2 pl-4 w-16">Hạng</th>
              <th className="pb-2">Người học</th>
              <th className="pb-2 text-right pr-4">XP tuần</th>
            </tr>
          </thead>
          <tbody>
            {rows.map((row) => {
              const isMe = row.userId === user?.id
              return (
                <tr
                  key={row.userId}
                  className={cn(
                    'transition-colors',
                    isMe
                      ? 'bg-blue-50 outline outline-2 outline-blue-200 rounded-xl'
                      : 'bg-slate-50/60 hover:bg-slate-100',
                  )}
                >
                  <td className="py-2.5 pl-4 rounded-l-xl">
                    <RankBadge rank={row.rank} />
                  </td>
                  <td className="py-2.5">
                    <div className="flex items-center gap-2.5">
                      <div className={cn(
                        'w-8 h-8 rounded-full flex items-center justify-center text-xs font-bold flex-shrink-0',
                        isMe
                          ? 'bg-blue-600 text-white ring-2 ring-blue-300 ring-offset-1'
                          : 'bg-slate-200 text-slate-600',
                      )}>
                        {initials(row.displayName)}
                      </div>
                      <span className={cn('text-sm font-bold', isMe && 'text-blue-600')}>
                        {isMe ? `${row.displayName} (Bạn)` : row.displayName}
                      </span>
                    </div>
                  </td>
                  <td className="py-2.5 pr-4 text-right rounded-r-xl">
                    <span className={cn('text-sm font-bold', isMe ? 'text-blue-600' : 'text-slate-600')}>
                      {row.xpEarned.toLocaleString('vi-VN')} XP
                    </span>
                  </td>
                </tr>
              )
            })}
          </tbody>
        </table>
      )}
    </div>
  )
}
