'use client'

import { useParams, useSearchParams, useRouter } from 'next/navigation'
import { UserCard } from './components/UserCard'
import { AboutSection } from './components/AboutSection'
import { GiftGrid } from './components/GiftGrid'
import UserBackground from './components/UserBackground'
import AlbumList from './components/AlbumList'
import { UserTab } from './types'
import { useGetAIUserBaseInfo } from '@/hooks/aiUser'
import { Tabs, TabsContent } from '@/components/ui/tabs'
import { AIUserProvider } from './context/aiUser'
import UserActionDropdown from './components/UserActionDropdown'
import UserProfileTabs from './components/UserProfileTabs'
import { useCallback } from 'react'

const UserPage = () => {
  const { userId } = useParams()
  const searchParams = useSearchParams()
  const router = useRouter()
  const { data } = useGetAIUserBaseInfo({ aiId: Number(userId) })
  const { introduction } = data || {}

  // 从 URL 参数中获取当前 tab，如果没有或无效则默认为 About
  const tabParam = searchParams.get('tab')
  const currentTab = (
    Object.values(UserTab).includes(tabParam as UserTab) ? tabParam : UserTab.About
  ) as UserTab

  // 处理 tab 切换
  const handleTabChange = useCallback(
    (newTab: string) => {
      const params = new URLSearchParams(searchParams.toString())
      params.set('tab', newTab)
      router.push(`/@${userId}?${params.toString()}`, { scroll: false })
    },
    [searchParams, router, userId]
  )

  return (
    <AIUserProvider>
      {data && (
        <div className="w-full bg-[#211a2b] px-16">
          <UserBackground />

          {/* 主要内容 */}
          <div className="relative flex justify-center pt-28 pb-20">
            <UserActionDropdown />

            {/* 左侧用户卡片 */}
            <div className="w-[368px]">
              <UserCard />
            </div>

            {/* 右侧内容区域 */}
            <div className="max-w-[752px] flex-1 px-6 pt-4">
              <Tabs value={currentTab} onValueChange={handleTabChange} className="w-full gap-4">
                <UserProfileTabs currentTab={currentTab} />

                {/* Tab 内容 */}
                <TabsContent value={UserTab.About} className="mt-0">
                  <div className="flex flex-col gap-4">
                    <AboutSection introduction={introduction ?? ''} />
                    <GiftGrid userId={userId as string} />
                  </div>
                </TabsContent>

                <TabsContent value={UserTab.Album} className="mt-0">
                  <AlbumList />
                </TabsContent>
              </Tabs>
            </div>
          </div>
        </div>
      )}
    </AIUserProvider>
  )
}

export default UserPage
