import type { Metadata } from 'next'
import { notFound } from 'next/navigation'
import Link from 'next/link'
import Image from 'next/image'
import { getPayload } from 'payload'
import config from '@payload-config'
import { SITE } from '@/lib/seo'
import { getSiteSettings } from '@/lib/site-settings'
import RichText from '@/components/RichText'
import { CATEGORY_LABELS, type PayloadBlog, blogCoverUrl } from '../page'
import { tagToSlug } from '../tag/[slug]/page'
import { getAuthor } from '@/lib/blog-authors'

export const revalidate = 3600

export async function generateStaticParams() {
  const payload = await getPayload({ config })
  const result = await payload.find({
    collection: 'blogs',
    where: { status: { equals: 'published' } },
    limit: 500,
    pagination: false,
    depth: 0,
  })
  return (result.docs as unknown as PayloadBlog[]).map(p => ({ slug: p.slug }))
}

export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }): Promise<Metadata> {
  const { slug } = await params
  const payload = await getPayload({ config })
  const result = await payload.find({
    collection: 'blogs',
    where: { slug: { equals: slug } },
    limit: 1,
    depth: 1,
  })
  const post = result.docs[0] as unknown as PayloadBlog | undefined
  if (!post) return {}

  const title       = post.seoTitle || `${post.title} | NCK Car Rental Dubai`
  const description = post.seoDesc  || post.excerpt || ''
  const image       = blogCoverUrl(post)

  const fallbackOg = "/media/ferrari-f8-tributo-rental-dubai-02.webp"
  const ogImg = image ?? fallbackOg
  return {
    title,
    description,
    alternates: { canonical: `${SITE.domain}/blog/${slug}/` },
    robots:     { index: true, follow: true },
    openGraph: {
      title,
      description,
      url:           `${SITE.domain}/blog/${slug}/`,
      siteName:      "NCK Car Rental",
      locale:        "en_AE",
      type:          'article',
      publishedTime: post.publishedAt,
      modifiedTime:  post.updatedAt ?? post.publishedAt,
      authors:       [post.author ?? SITE.name],
      images:        [{ url: ogImg, width: 1200, height: 630, alt: post.title }],
    },
    twitter: {
      card:        'summary_large_image',
      title,
      description,
      images:      [ogImg],
    },
  }
}

export default async function BlogPostPage({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params
  const [payload, s] = await Promise.all([getPayload({ config }), getSiteSettings()])

  const result = await payload.find({
    collection: 'blogs',
    where: { slug: { equals: slug } },
    limit: 1,
    depth: 1,
  })

  const post = result.docs[0] as unknown as PayloadBlog | undefined
  if (!post || post.status !== 'published') notFound()

  const relatedRes = await payload.find({
    collection: 'blogs',
    where: {
      and: [
        { status: { equals: 'published' } },
        ...(post.category ? [{ category: { equals: post.category } }] : []),
        { slug: { not_equals: slug } },
      ],
    },
    sort: '-publishedAt',
    limit: 3,
    depth: 1,
  })
  const related = relatedRes.docs as unknown as PayloadBlog[]

  const image      = blogCoverUrl(post)
  const author     = getAuthor(post.author ?? '')
  const catLabel   = post.category ? (CATEGORY_LABELS[post.category] ?? post.category) : null
  const dateStr    = new Date(post.publishedAt).toLocaleDateString('en-AE', { day: 'numeric', month: 'long', year: 'numeric' })
  const shareText  = encodeURIComponent(`${post.title} - ${SITE.domain}/blog/${slug}/`)
  const shareWaUrl = `https://wa.me/?text=${shareText}`
  const waMsg      = encodeURIComponent(`Hi, I read your article "${post.title}" and would like to rent a car in Dubai. Can you help?`)
  const waUrl      = `https://wa.me/${s.whatsapp1}?text=${waMsg}`

  const articleJsonLd = {
    '@context':        'https://schema.org',
    '@type':           'BlogPosting',
    headline:          post.title,
    description:       post.excerpt ?? '',
    url:               `${SITE.domain}/blog/${slug}/`,
    datePublished:     post.publishedAt,
    dateModified:      post.updatedAt ?? post.publishedAt,
    author: author
      ? { '@type': 'Person', name: author.name, jobTitle: author.role, worksFor: { '@type': 'Organization', name: SITE.name, url: SITE.domain } }
      : { '@type': 'Organization', name: SITE.name, url: SITE.domain },
    publisher: {
      '@type': 'Organization',
      name:    SITE.name,
      url:     SITE.domain,
      logo:    { '@type': 'ImageObject', url: `${SITE.domain}/logo.png` },
    },
    ...(image && { image: `${SITE.domain}${image}` }),
    mainEntityOfPage:  { '@type': 'WebPage', '@id': `${SITE.domain}/blog/${slug}/` },
    ...(post.tags?.length && { keywords: post.tags.map(t => t.tag).join(', ') }),
  }

  const breadcrumbJsonLd = {
    '@context': 'https://schema.org',
    '@type':    'BreadcrumbList',
    itemListElement: [
      { '@type': 'ListItem', position: 1, name: 'Home', item: `${SITE.domain}/` },
      { '@type': 'ListItem', position: 2, name: 'Blog', item: `${SITE.domain}/blog/` },
      { '@type': 'ListItem', position: 3, name: post.title, item: `${SITE.domain}/blog/${slug}/` },
    ],
  }

  return (
    <>
      <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(articleJsonLd) }} />
      <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(breadcrumbJsonLd) }} />

      {/* Cover image */}
      {image && (
        <div className="relative w-full h-64 sm:h-80 lg:h-[440px] bg-navy-900">
          <Image src={image} alt={post.title} fill className="object-cover" priority />
          <div className="absolute inset-0 bg-gradient-to-t from-navy-900/70 via-navy-900/10 to-transparent" />
        </div>
      )}

      <div className="section-wrap">
        <div className="max-w-3xl mx-auto">

          {/* Breadcrumb */}
          <nav className="flex items-center gap-1.5 text-xs text-[#8892a4] pt-7 pb-5" aria-label="Breadcrumb">
            <Link href="/" className="hover:text-brand transition-colors">Home</Link>
            <span>/</span>
            <Link href="/blog" className="hover:text-brand transition-colors">Blog</Link>
            <span>/</span>
            <span className="text-[#3a4051] truncate max-w-[200px] sm:max-w-xs">{post.title}</span>
          </nav>

          {/* Category + read time */}
          <div className="flex flex-wrap items-center gap-2 mb-4">
            {catLabel && (
              <span className="bg-brand/10 text-brand text-xs font-bold px-3 py-1.5 rounded-full">
                {catLabel}
              </span>
            )}
            {post.readTime && (
              <span className="text-[#8892a4] text-xs flex items-center gap-1">
                <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
                {post.readTime} min read
              </span>
            )}
          </div>

          {/* Title */}
          <h1 className="text-3xl lg:text-4xl font-black text-navy-900 leading-tight mb-4">
            {post.title}
          </h1>

          {/* Excerpt / standfirst */}
          {post.excerpt && (
            <p className="text-lg text-[#5c6472] leading-relaxed mb-6 pb-6 border-b border-[#e2e6ed]">
              {post.excerpt}
            </p>
          )}

          {/* Author row */}
          <div className="flex items-center justify-between gap-4 mb-10">
            <div className="flex items-center gap-3">
              <div
                className="w-9 h-9 rounded-full text-white font-black text-sm flex items-center justify-center flex-shrink-0"
                style={{ background: author?.color ?? '#1359ba' }}
              >
                {author?.initials ?? 'N'}
              </div>
              <div>
                <p className="text-sm font-semibold text-[#1a1f2e]">{post.author ?? 'NCK Car Rental'}</p>
                <p className="text-xs text-[#8892a4]">{author?.role ? `${author.role} · ` : ''}{dateStr}</p>
              </div>
            </div>

            {/* Share */}
            <a
              href={shareWaUrl}
              target="_blank"
              rel="noopener noreferrer"
              className="flex items-center gap-1.5 text-xs text-white bg-emerald-500 hover:bg-emerald-600 px-3.5 py-2 rounded-xl transition-colors flex-shrink-0"
            >
              <svg className="w-3.5 h-3.5" fill="currentColor" viewBox="0 0 24 24">
                <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413Z"/>
              </svg>
              Share
            </a>
          </div>

          {/* Article content */}
          <article className="mb-12">
            <RichText content={post.content} />
          </article>

          {/* Author bio box */}
          {author ? (
            <div className="border border-[#e2e6ed] rounded-2xl p-6 mb-10 bg-[#f8faff]">
              <p className="text-xs font-bold uppercase tracking-widest text-[#8892a4] mb-4">About the author</p>
              <div className="flex gap-4 items-start">
                <div
                  className="w-14 h-14 rounded-full flex-shrink-0 flex items-center justify-center text-white font-black text-xl shadow-md"
                  style={{ background: author.color }}
                >
                  {author.initials}
                </div>
                <div className="flex-1 min-w-0">
                  <p className="font-black text-navy-900 text-lg leading-tight">{author.name}</p>
                  <p className="text-brand text-sm font-semibold mb-3">{author.role} · NCK Car Rental Dubai</p>
                  <p className="text-[#5c6472] text-sm leading-relaxed mb-3">{author.bio}</p>
                  <div className="flex flex-wrap gap-3 text-xs text-[#8892a4]">
                    <span className="flex items-center gap-1.5">
                      <svg className="w-3.5 h-3.5 text-brand" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/>
                      </svg>
                      {author.years}
                    </span>
                    <span className="flex items-center gap-1.5">
                      <svg className="w-3.5 h-3.5 text-brand" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/>
                      </svg>
                      {author.funFact}
                    </span>
                  </div>
                </div>
              </div>
            </div>
          ) : (
            <div className="border border-[#e2e6ed] rounded-2xl p-5 mb-10 bg-[#f8faff] flex items-center gap-4">
              <div className="w-12 h-12 rounded-full bg-brand/10 flex-shrink-0 flex items-center justify-center text-brand font-black text-lg">N</div>
              <div>
                <p className="font-bold text-navy-900 text-sm">{post.author ?? 'NCK Car Rental'}</p>
                <p className="text-xs text-[#8892a4] mt-0.5">NCK Car Rental Dubai · Delivering cars across Dubai since {new Date().getFullYear() - 10}</p>
              </div>
            </div>
          )}

          {/* Tags */}
          {post.tags && post.tags.length > 0 && (
            <div className="flex flex-wrap gap-2 mb-10 pb-10 border-b border-[#e2e6ed]">
              {post.tags.map(t => (
                <Link
                  key={t.tag}
                  href={`/blog/tag/${tagToSlug(t.tag)}`}
                  className="bg-[#f0f5ff] hover:bg-brand text-brand hover:text-white text-xs font-medium px-3 py-1.5 rounded-full transition-colors"
                >
                  #{t.tag}
                </Link>
              ))}
            </div>
          )}

          {/* CTA block */}
          <div className="bg-navy-900 rounded-3xl p-8 lg:p-10 mb-12 text-center">
            <p className="text-white/50 text-xs font-bold uppercase tracking-widest mb-2">Ready to Ride?</p>
            <h3 className="text-2xl lg:text-3xl font-black text-white mb-2">Book Your Car in Dubai</h3>
            <p className="text-white/55 text-sm mb-7">Free delivery · No deposit · 24/7 support</p>
            <div className="flex flex-col sm:flex-row gap-3 justify-center">
              <a
                href={waUrl}
                target="_blank"
                rel="noopener noreferrer"
                className="flex items-center justify-center gap-2 bg-emerald-500 hover:bg-emerald-600 text-white font-bold px-6 py-3 rounded-2xl transition-all"
              >
                <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
                  <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413Z"/>
                </svg>
                WhatsApp Us
              </a>
              <Link
                href="/all-cars"
                className="flex items-center justify-center gap-2 bg-white/10 hover:bg-white/20 text-white font-bold px-6 py-3 rounded-2xl transition-all"
              >
                Browse All Cars →
              </Link>
            </div>
          </div>
        </div>

        {/* Related posts */}
        {related.length > 0 && (
          <div className="max-w-5xl mx-auto mb-16">
            <h2 className="text-xl font-bold text-navy-900 mb-6">More Articles</h2>
            <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-5">
              {related.map(p => {
                const pImg = blogCoverUrl(p)
                return (
                  <Link
                    key={p.id}
                    href={`/blog/${p.slug}`}
                    className="group block bg-white rounded-2xl overflow-hidden border border-[#e2e6ed] hover:shadow-float transition-shadow"
                  >
                    <div className="relative aspect-[16/9] bg-navy-100">
                      {pImg ? (
                        <Image src={pImg} alt={p.title} fill className="object-cover group-hover:scale-105 transition-transform duration-500" />
                      ) : (
                        <div className="absolute inset-0 bg-gradient-to-br from-navy-700 to-brand" />
                      )}
                    </div>
                    <div className="p-4">
                      {p.category && (
                        <p className="text-brand text-xs font-bold uppercase tracking-widest mb-1.5">
                          {CATEGORY_LABELS[p.category] ?? p.category}
                        </p>
                      )}
                      <h3 className="font-bold text-[#0b1845] text-sm leading-snug group-hover:text-brand transition-colors line-clamp-2 mb-2">
                        {p.title}
                      </h3>
                      <p className="text-xs text-[#8892a4]">
                        {new Date(p.publishedAt).toLocaleDateString('en-AE', { day: 'numeric', month: 'short', year: 'numeric' })}
                      </p>
                    </div>
                  </Link>
                )
              })}
            </div>
          </div>
        )}
      </div>
    </>
  )
}
