import UserPage from './user-page'
import { HydrationBoundary } from '@tanstack/react-query'
import { dehydrate } from '@tanstack/react-query'
import { QueryClient } from '@tanstack/react-query'
import { aiUserKeys } from '@/lib/query-keys'
import { userService } from '@/services/user'
import { ApiError } from '@/types/api'
import { notFound, redirect } from 'next/navigation'
import { headers } from 'next/headers'
import { isMobileDevice } from '@/utils/device'

export const generateMetadata = async ({ params }: { params: Promise<{ userId: string }> }) => {
  const { userId } = await params
  try {
    const resp = await userService.getSEOUserBaseInfo({ aiId: Number(userId) })
    const { nickname, homeImageUrl } = resp || {}

    return {
      title: `${nickname} - Crushlevel AI`,
      description: `${nickname}`,
      openGraph: {
        title: `Crushlevel AI`,
        description: `Grow your love story with CrushLevel AI—From ‘Hi’ to ‘I Do', sparked by every chat`,
        images: {
          url: homeImageUrl,
          width: 720,
          height: 1280,
          alt: `${nickname} - Crushlevel AI`,
        },
        siteName: 'Crushlevel AI',
        type: 'website',
        url: `https://www.crushlevel.com/@${userId}`,
      },
      twitter: {
        title: `Crushlevel AI`,
        description: `Grow your love story with CrushLevel AI—From ‘Hi’ to ‘I Do', sparked by every chat`,
        images: {
          url: homeImageUrl,
          width: 720,
          height: 1280,
          alt: `${nickname} - Crushlevel AI`,
        },
        siteName: 'Crushlevel AI',
        type: 'website',
        url: `https://www.crushlevel.com/@${userId}`,
      },
    }
  } catch (error) {
    return {
      title: `Crushlevel AI`,
      description: `Grow your love story with CrushLevel AI—From ‘Hi’ to ‘I Do', sparked by every chat`,
      openGraph: {
        title: `Crushlevel AI`,
        description: `Grow your love story with CrushLevel AI—From ‘Hi’ to ‘I Do', sparked by every chat`,
      },
    }
  }
}

const Page = async ({ params }: { params: Promise<{ userId: string }> }) => {
  const { userId } = await params

  // 检测移动端设备并重定向到分享页面
  const headersList = await headers()
  const userAgent = headersList.get('user-agent') || ''

  if (isMobileDevice(userAgent)) {
    redirect(`/share/${userId}`)
  }

  const queryClient = new QueryClient()

  // try {
  //   // 使用 fetchQuery 替代 prefetchQuery，因为 fetchQuery 会抛出错误
  //   await queryClient.fetchQuery({
  //     queryKey: aiUserKeys.tempBaseInfo({ aiId: Number(userId) }),
  //     queryFn: () => userService.getAIUserBaseInfo({ aiId: Number(userId) }),
  //   });
  // } catch (error) {
  //   if (error instanceof ApiError && error.errorCode === "10010012") {
  //     notFound();
  //   }
  // }

  return (
    <HydrationBoundary state={dehydrate(queryClient)}>
      <UserPage />
    </HydrationBoundary>
  )
}

export default Page
