import React from 'react';
import Link from 'next/link';
import { notFound } from 'next/navigation';
import { ArrowLeft, ArrowRight, User, Calendar, Share2 } from 'lucide-react';
import { sanitizeHTML } from '../../../lib/sanitize';
import { prisma } from '../../../lib/prisma';
import BlogShareButtons from '../../../components/BlogShareButtons';
import { Metadata } from 'next';

interface Props {
  params: Promise<{ id: string }>;
}

// Style spécifique pour empêcher strictement la coupure des mots tout en justifiant le texte
const noBreakStyle = `
  #blog-content, 
  #blog-content p, 
  #blog-content li, 
  #blog-content span, 
  #blog-content strong {
    word-break: normal !important;
    overflow-wrap: break-word !important;
    hyphens: none !important;
    line-break: normal !important;
    text-align: justify !important;
    text-justify: inter-word !important;
  }
  
  /* Sécurité supplémentaire pour les navigateurs mobiles */
  .prose * {
    word-break: normal !important;
    hyphens: none !important;
  }
`;

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { id } = await params;
  const post = await prisma.blogPost.findFirst({
    where: {
      OR: [{ id: id }, { slug: id }],
      publishedAt: { lte: new Date() },
      status: 'PUBLISHED'
    }
  });

  if (!post) return { title: 'Article non trouvé' };

  return {
    title: post.metaTitle || post.title,
    description: post.metaDescription || post.excerpt,
    keywords: post.tags,
    openGraph: {
      title: post.metaTitle || post.title,
      description: post.metaDescription || post.excerpt,
      images: [post.imageUrl],
      type: 'article',
    }
  };
}

export default async function BlogPostPage({ params }: Props) {
  const { id } = await params;
  const post = await prisma.blogPost.findFirst({
    where: {
      OR: [{ id: id }, { slug: id }],
      publishedAt: { lte: new Date() },
      status: 'PUBLISHED'
    }
  });

  if (!post) {
    notFound();
  }

  return (
    <article className="bg-gray-50 min-h-screen py-12 relative">
      {/* Injection du style de force pour le texte */}
      <style dangerouslySetInnerHTML={{ __html: noBreakStyle }} />

      <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 flex gap-4 lg:gap-8 justify-center relative">
        {/* Conteneur principal de l'article */}
        <div className="w-[calc(100%-3rem)] sm:w-full max-w-3xl relative">

          {/* Navigation */}
          <div className="mb-8">
            <Link href="/blog" className="inline-flex items-center text-gray-500 hover:text-brand-600 text-sm font-medium transition-colors">
              <ArrowLeft className="w-4 h-4 mr-1" /> Retour aux articles
            </Link>
          </div>

          <div className="bg-white rounded-xl shadow-sm p-6 md:p-10 border border-gray-100 relative z-10">
            {/* Image d'en-tête */}
          <div className="w-full h-64 md:h-80 relative mb-8 rounded-lg overflow-hidden">
            <img
              src={post.imageUrl}
              alt={post.title}
              className="w-full h-full object-cover"
            />
          </div>

          {/* Header de l'article */}
          <header className="mb-8 border-b border-gray-100 pb-8">
            <div className="flex flex-wrap items-center gap-4 text-sm text-gray-500 mb-4">
              <span className="flex items-center">
                <User className="w-4 h-4 mr-1 text-brand-500" />
                {post.author}
              </span>
              <span className="flex items-center">
                <Calendar className="w-4 h-4 mr-1 text-brand-500" />
                {new Date(post.date).toLocaleDateString('fr-FR', { day: 'numeric', month: 'long', year: 'numeric' })}
              </span>
              {post.tags.length > 0 ? (
                post.tags.map(tag => (
                  <span key={tag} className="px-2 py-1 bg-brand-50 text-brand-700 rounded text-xs font-semibold uppercase tracking-wide">
                    {tag}
                  </span>
                ))
              ) : (
                <span className="px-2 py-1 bg-brand-50 text-brand-700 rounded text-xs font-semibold uppercase tracking-wide">
                  Article
                </span>
              )}
            </div>
            <h1 className="text-3xl md:text-4xl font-serif font-bold text-gray-900 leading-tight">
              {post.title}
            </h1>
          </header>

          {/* Contenu de l'article */}
          <div className="prose prose-lg prose-orange max-w-none text-gray-600">
            {/* Résumé / Lead */}
            <p className="lead text-xl text-gray-500 font-serif italic mb-6 border-b border-gray-100 pb-6">
              {post.excerpt}
            </p>

            {/* Corps du texte avec ID pour le contrôle CSS */}
            <div
              id="blog-content"
              className="mt-6"
              dangerouslySetInnerHTML={{ __html: sanitizeHTML(post.content) }}
            />
          </div>

          {/* Partage / Footer CTA */}
          <div className="mt-12 pt-8 border-t border-gray-100">
            <div className="bg-brand-50 rounded-xl p-6 md:p-8 flex flex-col md:flex-row justify-between items-center gap-6">
              <div className="text-center md:text-left">
                <h3 className="text-xl font-bold text-brand-900 mb-1">Vous avez aimé cet article ?</h3>
                <p className="text-brand-700">Explorez d'autres contenus exclusifs sur l'afropreneuriat.</p>
              </div>
              <Link 
                href="/blog" 
                className="inline-flex items-center px-8 py-3 bg-brand-600 text-white font-bold rounded-lg hover:bg-brand-700 transition-all hover:scale-105 shadow-lg shadow-brand-200"
              >
                Voir plus d'articles
                <ArrowRight className="ml-2 w-5 h-5" />
              </Link>
            </div>
          </div>
        </div>
        </div>

        {/* Sidebar flottante verticale à droite (suit l'article et s'arrête à la fin) */}
        <div className="w-10 shrink-0 relative">
          <div className="sticky top-32 z-50">
            <BlogShareButtons title={post.title} />
          </div>
        </div>

      </div>
    </article>
  );
}