import { notFound } from 'next/navigation'
import type { Metadata } from 'next'
import { getTranslations } from 'next-intl/server'
import JsonLd from '@/components/frontend/seo/JsonLd'
import AuthorPageClient from '@/components/frontend/blog/AuthorPageClient'
import { getBlogAuthorPage } from '@/lib/db/queries/getBlogPosts'
import { getDefaultLanguage, getLanguages } from '@/lib/db/queries/getlanguages'
import { getSiteInfo } from '@/lib/db/queries/getSiteInfo'
import { buildLocalizedPath } from '@/lib/i18n/buildLocalizedPath'

const APP_URL = (process.env.NEXT_PUBLIC_APP_URL ?? 'http://localhost:3000').replace(/\/$/, '')
const POSTS_PER_PAGE = 9

interface AuthorPageProps {
  params: Promise<{ locale: string; slug: string }>
  searchParams: Promise<{ page?: string }>
}

function decodeSlug(slug: string): string {
  try {
    return decodeURIComponent(slug)
  } catch {
    return slug
  }
}

export async function generateMetadata({ params }: AuthorPageProps): Promise<Metadata> {
  const { locale, slug } = await params
  const [data, t, defaultLanguage, siteInfo, languages] = await Promise.all([
    getBlogAuthorPage(decodeSlug(slug), locale, { page: 1, limit: 1 }),
    getTranslations({ locale, namespace: 'BlogPage' }),
    getDefaultLanguage(),
    getSiteInfo(),
    getLanguages(),
  ])
  if (!data) return {}

  const { author } = data
  const defaultLocale = defaultLanguage?.code ?? 'en'
  const path = `/blogs/author/${author.slug}`
  const title = `${t('authorMetaTitle', { name: author.name })} | ${siteInfo.siteName}`
  const description = author.bio?.slice(0, 160) || t('authorMetaDescription', { name: author.name, siteName: siteInfo.siteName })

  // Author slugs aren't per-language, so every locale has the same page.
  const languageAlternates: Record<string, string> = {}
  for (const lang of languages) {
    languageAlternates[lang.code] = `${APP_URL}${buildLocalizedPath(lang.code, defaultLocale, path)}`
  }

  return {
    title,
    description,
    alternates: {
      canonical: `${APP_URL}${buildLocalizedPath(locale, defaultLocale, path)}`,
      languages: { ...languageAlternates, 'x-default': `${APP_URL}${buildLocalizedPath(defaultLocale, defaultLocale, path)}` },
    },
    openGraph: {
      title,
      description,
      siteName: siteInfo.siteName,
      type: 'profile',
      url: `${APP_URL}${buildLocalizedPath(locale, defaultLocale, path)}`,
      images: author.imageUrl ? [{ url: author.imageUrl, alt: author.name }] : undefined,
    },
    twitter: { card: 'summary', title, description },
  }
}

export default async function BlogAuthorPage({ params, searchParams }: AuthorPageProps) {
  const { locale, slug } = await params
  const { page: pageParam } = await searchParams
  const page = Math.max(1, Number(pageParam) || 1)

  const [data, defaultLanguage, siteInfo] = await Promise.all([
    getBlogAuthorPage(decodeSlug(slug), locale, { page, limit: POSTS_PER_PAGE }),
    getDefaultLanguage(),
    getSiteInfo(),
  ])
  // Unknown, inactive or deleted author → 404.
  if (!data) notFound()

  const defaultLocale = defaultLanguage?.code ?? 'en'
  const pageUrl = `${APP_URL}${buildLocalizedPath(locale, defaultLocale, `/blogs/author/${data.author.slug}`)}`
  const sameAs = [data.author.website, data.author.facebook, data.author.twitter, data.author.instagram, data.author.linkedin]
    .filter(Boolean)

  const schemas = [
    {
      '@context': 'https://schema.org',
      '@type': 'ProfilePage',
      url: pageUrl,
      mainEntity: {
        '@type': 'Person',
        name: data.author.name,
        description: data.author.bio ?? undefined,
        image: data.author.imageUrl ?? undefined,
        url: pageUrl,
        sameAs: sameAs.length > 0 ? sameAs : undefined,
      },
    },
    {
      '@context': 'https://schema.org',
      '@type': 'BreadcrumbList',
      itemListElement: [
        { '@type': 'ListItem', position: 1, name: 'Home', item: APP_URL },
        { '@type': 'ListItem', position: 2, name: 'Blog', item: `${APP_URL}${buildLocalizedPath(locale, defaultLocale, '/blogs')}` },
        { '@type': 'ListItem', position: 3, name: data.author.name, item: pageUrl },
      ],
    },
  ]

  return (
    <>
      <JsonLd data={schemas} />
      <AuthorPageClient
        author={data.author}
        posts={data.posts}
        total={data.total}
        page={page}
        totalPages={data.totalPages}
        siteName={siteInfo.siteName}
      />
    </>
  )
}
