'use client'

import { useMemo } from 'react'
import LargeRankCard from './LargeRankCard'
import SmallRankCard from './SmallRankCard'
import { AiChatRankOutput, AiHeartbeatRankOutput, AiGiftRankOutput } from '@/services/home/types'
import { RankType } from '@/types/global'
import { usePrefetchRoutes } from '@/hooks/useGlobalPrefetchRoutes'

interface TopHeaderProps {
  rankData: AiChatRankOutput[] | AiHeartbeatRankOutput[] | AiGiftRankOutput[]
  rankType: RankType
  isLoading?: boolean
}

export default function TopHeader({ rankData, rankType, isLoading }: TopHeaderProps) {
  const topThree = useMemo(() => (rankData || []).slice(0, 3), [rankData])
  const chatRoutes = useMemo(
    () => topThree.map((item) => (item?.aiId ? `/chat/${item.aiId}` : null)),
    [topThree]
  )
  usePrefetchRoutes(chatRoutes, { limit: 3 })

  if (isLoading) {
    return (
      <div className="mx-auto mt-6 max-w-[624px]">
        <div className="flex w-full items-center gap-4">
          <div className="flex-1 py-12">
            <div className="bg-surface-nest-normal aspect-[240/360] w-full animate-pulse rounded-b-lg" />
          </div>
          <div className="bg-surface-nest-normal aspect-[240/360] w-[38.5%] animate-pulse rounded-b-lg" />
          <div className="flex-1 py-12">
            <div className="bg-surface-nest-normal aspect-[240/360] w-full animate-pulse rounded-b-lg" />
          </div>
        </div>
      </div>
    )
  }

  if (!rankData || rankData.length === 0) {
    return (
      <div className="mx-auto mt-6 max-w-[624px]">
        <div className="flex h-64 items-center justify-center">
          <div className="text-txt-secondary-normal">No leaderboard data yet</div>
        </div>
      </div>
    )
  }

  const firstPlace = topThree[0]
  const secondPlace = topThree[1]
  const thirdPlace = topThree[2]

  return (
    <div className="mx-auto mt-6 max-w-[624px]">
      <div className="flex w-full items-center gap-4">
        {/* 第二名 */}
        <SmallRankCard item={secondPlace} rankType={rankType} rank={2} />

        {/* 第一名 */}
        <LargeRankCard item={firstPlace} rankType={rankType} />

        {/* 第三名 */}
        <SmallRankCard item={thirdPlace} rankType={rankType} rank={3} />
      </div>
    </div>
  )
}
