import { Metadata } from 'next';
import { notFound } from 'next/navigation';
import Image from 'next/image';
import Link from 'next/link';

export const dynamic = 'force-dynamic';
import { Calendar, User, Clock, Facebook, Twitter, MessageCircle, ArrowLeft, Eye } from 'lucide-react';
import { SITE_CONFIG } from '@/lib/constants';
import Sidebar from '@/components/Sidebar';
import HavadisAssistant from '@/components/HavadisAssistant';
import ArticleContent from '@/components/ArticleContent';
import InstagramFeaturedShowcase from '@/components/InstagramFeaturedShowcase';
import CategoryWidgets from '@/components/CategoryWidgets';
import RelatedInContent from '@/components/RelatedInContent';
import AdBanner, { MobileAdBanner, SidebarAd } from '@/components/AdBanner';
import { ArticleBacklinks, SidebarBacklinks } from '@/components/BacklinkArea';

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

async function getArticle(slug: string) {
  try {
    const prisma = (await import('@/lib/db')).default;

    // 1. Önce doğrudan unique slug ile ara
    let article = await prisma.article.findUnique({
      where: { slug },
    });

    // 2. Eğer bulunamazsa, büyük/küçük harf duyarsız ara (Plesk DB collation farkı için)
    if (!article) {
      console.log(`🔍 Slug bulunamadı, insensitive araması yapılıyor: ${slug}`);
      article = await prisma.article.findFirst({
        where: {
          OR: [
            { slug: { equals: slug } },
            { slug: { equals: decodeURIComponent(slug) } }
          ]
        }
      });
    }

    if (article) {
      // Görüntülenme sayısını artır (Hata oluşursa haberi göstermeyi engellemesin)
      prisma.article.update({
        where: { id: article.id },
        data: { viewCount: { increment: 1 } },
      }).catch(e => console.error('View count update error:', e));
    }

    return article;
  } catch (error) {
    console.error(`❌ getArticle Hatası (Slug: ${slug}):`, error);
    return null;
  }
}

async function getRelatedArticles(category: string, currentId: number) {
  try {
    const prisma = (await import('@/lib/db')).default;
    return prisma.article.findMany({
      where: {
        category,
        isPublished: true,
        id: { not: currentId },
      },
      orderBy: { publishedAt: 'desc' },
      take: 4,
    });
  } catch {
    return [];
  }
}

async function getPopularArticles() {
  try {
    const prisma = (await import('@/lib/db')).default;
    return prisma.article.findMany({
      where: { isPublished: true },
      orderBy: { viewCount: 'desc' },
      take: 5,
    });
  } catch {
    return [];
  }
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { slug } = await params;

  let article = null;
  try {
    const prisma = (await import('@/lib/db')).default;
    article = await prisma.article.findUnique({
      where: { slug },
      select: { title: true, summary: true, imageUrl: true, publishedAt: true },
    });
  } catch {
    // DB error
  }

  if (!article) {
    return { title: 'Haber Bulunamadı' };
  }

  // Description max 155 karakter (SEO için ideal)
  const metaDescription = article.summary.length > 155
    ? article.summary.substring(0, 152) + '...'
    : article.summary;

  // Canonical URL
  const canonicalUrl = `${SITE_CONFIG.url}/haber/${slug}`;

  return {
    title: article.title,
    description: metaDescription,
    alternates: {
      canonical: canonicalUrl,
    },
    openGraph: {
      title: article.title,
      description: metaDescription,
      type: 'article',
      publishedTime: article.publishedAt.toISOString(),
      images: article.imageUrl ? [{ url: article.imageUrl, width: 1200, height: 630 }] : [],
      siteName: SITE_CONFIG.name,
      url: canonicalUrl,
    },
    twitter: {
      card: 'summary_large_image',
      title: article.title,
      description: metaDescription,
      images: article.imageUrl ? [article.imageUrl] : [],
    },
  };
}

function formatDate(date: Date): string {
  return new Date(date).toLocaleDateString('tr-TR', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  });
}

function estimateReadTime(content: string): string {
  const words = content.split(/\s+/).length;
  const minutes = Math.ceil(words / 200);
  return `${minutes} dk`;
}

export default async function ArticlePage({ params }: Props) {
  const { slug } = await params;
  const [article, popularArticles] = await Promise.all([
    getArticle(slug),
    getPopularArticles(),
  ]);

  if (!article) {
    notFound();
  }

  const relatedArticles = await getRelatedArticles(article.category, article.id);

  // JSON-LD Schema
  const jsonLd = {
    '@context': 'https://schema.org',
    '@type': 'NewsArticle',
    headline: article.title,
    description: article.summary,
    image: article.imageUrl,
    datePublished: article.publishedAt.toISOString(),
    dateModified: article.updatedAt.toISOString(),
    author: {
      '@type': 'Organization',
      name: SITE_CONFIG.name,
      url: SITE_CONFIG.url,
    },
    publisher: {
      '@type': 'Organization',
      name: SITE_CONFIG.name,
      logo: {
        '@type': 'ImageObject',
        url: `${SITE_CONFIG.url}/images/logo.png`,
      },
    },
    mainEntityOfPage: {
      '@type': 'WebPage',
      '@id': `${SITE_CONFIG.url}/haber/${article.slug}`,
    },
  };

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

      <article className="max-w-7xl mx-auto px-4 py-8">
        {/* Breadcrumb */}
        <nav className="flex items-center gap-2 text-sm text-gray-500 mb-6">
          <Link href="/" className="hover:text-red-600 flex items-center gap-1">
            <ArrowLeft size={16} />
            Ana Sayfa
          </Link>
          <span>/</span>
          <Link href={`/kategori/${article.category.toLowerCase()}`} className="hover:text-red-600">
            {article.category}
          </Link>
        </nav>

        <div className="flex flex-col lg:flex-row gap-12">
          <div className="lg:w-2/3">
            {/* Header */}
            <header className="mb-8">
              <div className="flex items-center gap-3 mb-4">
                <span className="inline-block px-4 py-1.5 bg-red-600 text-white text-xs font-bold uppercase rounded-full">
                  {article.category}
                </span>
                <span className="inline-flex items-center gap-1.5 px-3 py-1.5 bg-gray-100 text-gray-600 text-xs font-medium rounded-full">
                  <Eye size={14} />
                  {article.viewCount.toLocaleString('tr-TR')} görüntülenme
                </span>
              </div>
              <h1 className="text-3xl md:text-4xl lg:text-5xl font-extrabold text-gray-900 leading-tight mb-6">
                {article.title}
              </h1>
              <div className="flex flex-wrap items-center gap-4 text-gray-500 text-sm pb-6 border-b border-gray-100">
                <span className="flex items-center gap-2">
                  <Calendar size={16} />
                  {formatDate(article.publishedAt)}
                </span>
                <span className="flex items-center gap-2">
                  <User size={16} />
                  <span className="font-medium text-gray-700">{article.source}</span>
                </span>
                <span className="flex items-center gap-2">
                  <Clock size={16} />
                  {estimateReadTime(article.content)} okuma
                </span>
              </div>
            </header>

            {/* Mobil Üst Reklam */}
            <MobileAdBanner slot="mobile_top" className="mb-4" />

            {/* Haber Başı Reklam - Desktop */}
            <AdBanner slot="article_top" className="hidden md:flex mb-6 justify-center" />

            {/* Featured Image - CLS önleme için aspect-ratio kullanıyoruz */}
            {article.imageUrl && (
              <div className="relative w-full aspect-video rounded-2xl overflow-hidden mb-8 bg-gray-100">
                <Image
                  src={article.imageUrl}
                  alt={article.title}
                  fill
                  className="object-cover"
                  priority
                  sizes="(max-width: 1024px) 100vw, 66vw"
                  placeholder="blur"
                  blurDataURL="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAAIAAoDASIAAhEBAxEB/8QAFgABAQEAAAAAAAAAAAAAAAAAAAUH/8QAIhAAAgEDAwUBAAAAAAAAAAAAAQIDAAQRBRIhBhMxQVFh/8QAFQEBAQAAAAAAAAAAAAAAAAAAAAX/xAAZEQACAwEAAAAAAAAAAAAAAAABAgADESH/2gAMAwEAAhEDEQA/AKuo9V6jqNy1zdXssk0m0O7EZbaMDOPQwB+UpSq1szDSCxm5Z//Z"
                />
              </div>
            )}

            {/* Article Content with AI Tools */}
            <ArticleContent
              content={article.content}
              summary={article.summary}
              title={article.title}
            />

            {/* Haber Ortası Reklam */}
            <AdBanner slot="article_middle" className="my-8 flex justify-center" />

            {/* Mobil Haber İçi Reklam */}
            <MobileAdBanner slot="mobile_article" className="my-6" />

            {/* İçerik içi ilgili haber önerisi */}
            <RelatedInContent
              currentCategory={article.category}
              currentId={article.id}
            />

            {/* Haber Sonu Reklam */}
            <AdBanner slot="article_bottom" className="my-8 flex justify-center" />

            {/* SEO Backlinks - Haber İçi */}
            <InstagramFeaturedShowcase articleSlug={article.slug} />

            {/* SEO Backlinks - Haber İçi */}
            <ArticleBacklinks />

            {/* Share Buttons */}
            <div className="py-8 border-t border-b border-gray-100 flex flex-wrap items-center gap-4 mb-12">
              <span className="text-sm font-bold text-gray-500 uppercase">Haberi Paylaş:</span>
              <div className="flex gap-2">
                <a
                  href={`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(`${SITE_CONFIG.url}/haber/${article.slug}`)}`}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="w-10 h-10 rounded-full bg-[#1877F2] text-white flex items-center justify-center hover:opacity-90 transition-opacity"
                  aria-label="Facebook'ta Paylaş"
                >
                  <Facebook size={20} />
                </a>
                <a
                  href={`https://twitter.com/intent/tweet?url=${encodeURIComponent(`${SITE_CONFIG.url}/haber/${article.slug}`)}&text=${encodeURIComponent(article.title)}`}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="w-10 h-10 rounded-full bg-[#1DA1F2] text-white flex items-center justify-center hover:opacity-90 transition-opacity"
                  aria-label="Twitter'da Paylaş"
                >
                  <Twitter size={20} />
                </a>
                <a
                  href={`https://wa.me/?text=${encodeURIComponent(`${article.title} - ${SITE_CONFIG.url}/haber/${article.slug}`)}`}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="w-10 h-10 rounded-full bg-[#25D366] text-white flex items-center justify-center hover:opacity-90 transition-opacity"
                  aria-label="WhatsApp'ta Paylaş"
                >
                  <MessageCircle size={20} />
                </a>
              </div>
            </div>

            {/* Related Articles */}
            {relatedArticles.length > 0 && (
              <section>
                <h2 className="text-2xl font-black mb-6 border-l-4 border-red-600 pl-4 uppercase">
                  İlgili Haberler
                </h2>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  {relatedArticles.map((related) => (
                    <Link
                      key={related.id}
                      href={`/haber/${related.slug}`}
                      className="group flex gap-4"
                    >
                      {related.imageUrl && (
                        <div className="relative w-24 h-24 flex-shrink-0 rounded-lg overflow-hidden bg-gray-100">
                          <Image
                            src={related.imageUrl}
                            alt={related.title}
                            fill
                            className="object-cover"
                            sizes="96px"
                            placeholder="blur"
                            blurDataURL="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAAIAAoDASIAAhEBAxEB/8QAFgABAQEAAAAAAAAAAAAAAAAAAAUH/8QAIhAAAgEDAwUBAAAAAAAAAAAAAQIDAAQRBRIhBhMxQVFh/8QAFQEBAQAAAAAAAAAAAAAAAAAAAAX/xAAZEQACAwEAAAAAAAAAAAAAAAABAgADESH/2gAMAwEAAhEDEQA/AKuo9V6jqNy1zdXssk0m0O7EZbaMDOPQwB+UpSq1szDSCxm5Z//Z"
                          />
                        </div>
                      )}
                      <div>
                        <h3 className="font-bold text-gray-900 group-hover:text-red-600 transition-colors line-clamp-2">
                          {related.title}
                        </h3>
                        <span className="text-xs text-gray-500">
                          {formatDate(related.publishedAt)}
                        </span>
                      </div>
                    </Link>
                  ))}
                </div>
              </section>
            )}
          </div>

          <aside className="lg:w-1/3 space-y-6">
            {/* Sidebar Üst Reklam */}
            <SidebarAd slot="sidebar_top" />

            {/* Kategori bazlı widget */}
            <CategoryWidgets category={article.category} />

            {/* Sidebar Orta Reklam */}
            <SidebarAd slot="sidebar_middle" />

            {/* Genel sidebar */}
            <Sidebar popularNews={popularArticles} />

            {/* Sidebar Alt Reklam */}
            <SidebarAd slot="sidebar_bottom" />

            {/* SEO Backlinks - Sidebar */}
            <SidebarBacklinks />
          </aside>
        </div>
      </article>

      <HavadisAssistant />
    </>
  );
}

