'use client'

import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { cn } from '@/lib/utils'
import { useState, useEffect } from 'react'
import { useSearchParams } from 'next/navigation'
import TopHeader from './components/TopHeader'
import RankingList from './components/RankingList'
import { useGetChatRank, useGetHeartbeatRank, useGetGiftRank } from '@/hooks/useHome'
import { RankType } from '@/types/global'
import Image from 'next/image'
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
import { IconButton } from '@/components/ui/button'

const LeaderboardPage = () => {
  const searchParams = useSearchParams()
  const typeFromUrl = searchParams.get('type')

  // 验证并设置初始 tab，确保 typeFromUrl 是有效的 RankType
  const getInitialTab = (): RankType => {
    if (typeFromUrl && Object.values(RankType).includes(typeFromUrl as RankType)) {
      return typeFromUrl as RankType
    }
    return RankType.CHAT
  }

  const [selectedTab, setSelectedTab] = useState<RankType>(getInitialTab())

  // 当 URL 参数变化时，更新选中的 tab
  useEffect(() => {
    const newTab = getInitialTab()
    setSelectedTab(newTab)
  }, [typeFromUrl])

  // 调用三个排行榜接口
  const { data: chatRankData, isLoading: chatLoading, error: chatError } = useGetChatRank()
  const {
    data: heartbeatRankData,
    isLoading: heartbeatLoading,
    error: heartbeatError,
  } = useGetHeartbeatRank()
  const { data: giftRankData, isLoading: giftLoading, error: giftError } = useGetGiftRank()

  const tabs = [
    { value: RankType.CHAT, label: 'Chat' },
    { value: RankType.CRUSH, label: 'Crush' },
    { value: RankType.GIFTS, label: 'Gifts' },
  ]

  // 根据选中的tab获取对应的数据
  const getCurrentRankData = () => {
    switch (selectedTab) {
      case RankType.CHAT:
        return { data: chatRankData, isLoading: chatLoading, error: chatError }
      case RankType.CRUSH:
        return { data: heartbeatRankData, isLoading: heartbeatLoading, error: heartbeatError }
      case RankType.GIFTS:
        return { data: giftRankData, isLoading: giftLoading, error: giftError }
      default:
        return { data: chatRankData, isLoading: chatLoading, error: chatError }
    }
  }

  const currentRankData = getCurrentRankData()

  const backgroundColorMap = {
    [RankType.CHAT]: 'linear-gradient(122.5deg, #F264A4 20.45%, #C241E6 100%)',
    [RankType.CRUSH]: 'linear-gradient(122.5deg, #D664F2 20.45%, #416DE6 100%)',
    [RankType.GIFTS]: 'linear-gradient(122.5deg, #FFC336 20.45%, #FF972F 100%)',
  }
  // return (background: linear-gradient(122.5deg, #F264A4 20.45%, #C241E6 100%);

  return (
    <div className="bg-background-default w-full">
      <div className="bg-background-default absolute top-0 right-0 bottom-0 left-0">
        <div
          className="absolute -top-[215px] h-[300px] w-[100%] opacity-50 blur-3xl"
          style={{
            background: backgroundColorMap[selectedTab],
          }}
        />
        <Image src="/images/leaderboard/bg.png" alt="Bg" fill className="object-cover" />
      </div>
      <div className="relative mx-auto w-full max-w-[752px]">
        <h1 className="txt-headline-m pt-12 text-center">Leaderboard</h1>
        <Tooltip>
          <TooltipTrigger asChild>
            <IconButton
              iconfont="icon-question"
              variant="tertiaryDark"
              size="small"
              className="absolute top-0 right-0"
            />
          </TooltipTrigger>
          <TooltipContent>
            <p>The hot chat list is ranked by the number of AI chat sessions.</p>
            <p>
              The heart list is ranked by the sum of the heart values generated by all the
              interlocutors of the AI character.
            </p>
            <p>
              The gift list is ranked by the sum of the gift value received by the AI character.
            </p>
          </TooltipContent>
        </Tooltip>
        <div className="mt-4 flex items-center justify-center">
          <Tabs
            className="h-auto rounded-none p-0"
            value={selectedTab}
            onValueChange={(value) => setSelectedTab(value as RankType)}
          >
            <TabsList>
              {tabs.map((tab) => (
                <TabsTrigger
                  key={tab.value}
                  value={tab.value}
                  className={cn(
                    'relative h-8 border-0 bg-transparent px-2 shadow-none',
                    'txt-title-m text-txt-secondary-normal',
                    'data-[state=active]:text-txt-primary-normal',
                    'data-[state=active]:bg-transparent',
                    'data-[state=active]:shadow-none',
                    'hover:text-txt-primary-normal',
                    'focus-visible:ring-0 focus-visible:ring-offset-0',
                    'flex cursor-pointer items-center justify-center'
                  )}
                >
                  <span className="whitespace-nowrap">{tab.label}</span>
                  {/* 活跃状态指示器 */}
                  <div
                    className={cn(
                      'bg-primary-normal absolute bottom-0 left-1/2 h-1 w-5 -translate-x-1/2 rounded-xs transition-opacity',
                      selectedTab === tab.value ? 'opacity-100' : 'opacity-0'
                    )}
                  />
                </TabsTrigger>
              ))}
            </TabsList>
          </Tabs>
        </div>

        {/* 排行榜内容 */}
        {
          <>
            <TopHeader
              rankData={currentRankData.data || []}
              rankType={selectedTab}
              isLoading={currentRankData.isLoading}
            />

            {/* 后续排名列表 */}
            {!currentRankData.isLoading && (
              <RankingList
                rankData={currentRankData.data || []}
                rankType={selectedTab}
                startFromRank={4}
              />
            )}
          </>
        }
      </div>
    </div>
  )
}

export default LeaderboardPage
