import { notFound } from 'next/navigation';
import Image from 'next/image';
import { getTranslations } from 'next-intl/server';
import { prisma } from '@/lib/prisma';
import { Container } from '@/components/ui/container';
import { BlogCard } from '@/components/cards/blog-card';
import { Reveal } from '@/components/ui/reveal';
import { buildMetadata } from '@/lib/seo';
import { JsonLd, articleSchema, breadcrumbSchema } from '@/lib/schema-org';
import type { Locale } from '@/i18n/config';

const SITE_URL = process.env.NEXT_PUBLIC_SITE_URL ?? 'http://localhost:3000';

async function getPost(slug: string, locale: Locale) {
  const post = await prisma.post.findUnique({
    where: { slug },
    include: {
      translations: { where: { locale } },
      author: { include: { translations: { where: { locale } } } },
      tags: { include: { translations: { where: { locale } } } }
    }
  });
  if (!post || !post.translations[0]) return null;
  return { ...post, t: post.translations[0] };
}

export async function generateMetadata({
  params: { locale, slug }
}: {
  params: { locale: Locale; slug: string };
}) {
  const post = await getPost(slug, locale);
  if (!post) return {};
  return buildMetadata({
    locale,
    path: `/blog/${slug}`,
    title: post.t.seoTitle ?? post.t.title,
    description: post.t.seoDescription ?? post.t.excerpt,
    image: post.coverImage ?? undefined,
    type: 'article'
  });
}

export default async function BlogDetailPage({
  params: { locale, slug }
}: {
  params: { locale: Locale; slug: string };
}) {
  const t = await getTranslations({ locale, namespace: 'blog' });
  const tNav = await getTranslations({ locale, namespace: 'nav' });
  const post = await getPost(slug, locale);
  if (!post) notFound();

  const related = await prisma.post.findMany({
    where: {
      published: true,
      id: { not: post.id },
      tags: { some: { id: { in: post.tags.map((tag) => tag.id) } } }
    },
    take: 3,
    include: { translations: { where: { locale } }, author: { include: { translations: { where: { locale } } } } }
  });

  const publishedAt = (post.publishedAt ?? post.createdAt).toISOString();

  return (
    <>
      <JsonLd
        data={articleSchema({
          title: post.t.title,
          description: post.t.excerpt,
          image: post.coverImage ?? undefined,
          authorName: post.author.translations[0]?.name ?? '',
          publishedAt,
          updatedAt: post.updatedAt.toISOString(),
          url: `${SITE_URL}/${locale}/blog/${slug}`
        })}
      />
      <JsonLd
        data={breadcrumbSchema([
          { name: tNav('blog'), url: `${SITE_URL}/${locale}/blog` },
          { name: post.t.title, url: `${SITE_URL}/${locale}/blog/${slug}` }
        ])}
      />

      <article>
        {post.coverImage && (
          <div className="relative h-64 w-full sm:h-96">
            <Image src={post.coverImage} alt={post.t.title} fill className="object-cover" />
          </div>
        )}
        <Container className="max-w-3xl py-16">
          <Reveal variant="up">
            <p className="text-sm text-volt-600">
              {new Date(publishedAt).toLocaleDateString(locale === 'ar' ? 'ar-TN' : 'fr-TN')}
              {post.readingMinutes ? ` · ${post.readingMinutes} ${t('minRead')}` : ''}
            </p>
          </Reveal>
          <Reveal variant="up" delay={80}>
            <h1 className="mt-2 font-display text-3xl font-semibold sm:text-4xl">{post.t.title}</h1>
          </Reveal>
          <Reveal variant="up" delay={140}>
            <p className="mt-2 text-sm text-graphite-900/50">
              {t('by')} {post.author.translations[0]?.name}
            </p>
          </Reveal>
          <Reveal variant="up" delay={200}>
            <div className="prose prose-graphite mt-8 max-w-none whitespace-pre-line text-graphite-900/80">
              {post.t.content}
            </div>
          </Reveal>
        </Container>
      </article>

      {related.length > 0 && (
        <Container className="pb-16">
          <Reveal variant="up">
            <h2 className="font-display text-xl font-semibold">{t('relatedArticles')}</h2>
          </Reveal>
          <div className="mt-6 grid gap-6 sm:grid-cols-3">
            {related
              .filter((r) => r.translations[0])
              .map((r) => (
                <BlogCard
                  key={r.slug}
                  locale={locale}
                  post={{
                    slug: r.slug,
                    coverImage: r.coverImage ?? undefined,
                    publishedAt: (r.publishedAt ?? r.createdAt).toISOString(),
                    readingMinutes: r.readingMinutes ?? undefined,
                    authorName: r.author.translations[0]?.name ?? '',
                    title: r.translations[0].title,
                    excerpt: r.translations[0].excerpt
                  }}
                />
              ))}
          </div>
        </Container>
      )}
    </>
  );
}
