import { notFound } from 'next/navigation';
import type { Metadata } from 'next';
import Link from 'next/link';
import { getPostBySlug, getPostsByLocale, getMediaById, getSiteInfo } from '@/lib/data';
import { getLocalizedPath } from '@/lib/i18n';
import { t } from '@/lib/i18n';
import { SEO } from '@/components/SEO';
import { LocaleSwitcher } from '@/components/LocaleSwitcher';
import { ContentRenderer } from '@/components/content/ContentRenderer';

interface PageProps {
  params: {
    slug: string;
    locale?: string;
  };
}

function RelatedPosts({ currentSlug, locale }: { currentSlug: string; locale: 'en' | 'de' }) {
  const allPosts = getPostsByLocale(locale);
  const currentPost = allPosts.find((p: any) => p.slug === currentSlug);
  
  if (!currentPost) return null;

  // Get recent posts (excluding current)
  const relatedPosts = allPosts
    .filter((p: any) => p.slug !== currentSlug)
    .slice(0, 3);

  if (relatedPosts.length === 0) return null;

  return (
    <div className="mt-16 border-t border-gray-200 pt-12">
      <h2 className="text-2xl font-bold text-gray-900 mb-6">
        {t('blog.relatedPosts', locale as 'en' | 'de')}
      </h2>
      <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
        {relatedPosts.map((post: any) => (
          <Link
            key={post.slug}
            href={getLocalizedPath(`/blog/${post.slug}`, locale as 'en' | 'de')}
            className="group block bg-white rounded-lg border border-gray-200 overflow-hidden hover:shadow-md transition-all"
          >
            {post.featuredImage && (() => {
              const media = getMediaById(post.featuredImage);
              return media ? (
                <div className="h-40 bg-gray-100 overflow-hidden">
                  <img
                    src={media.localPath}
                    alt={post.title}
                    className="h-full w-full object-cover group-hover:scale-105 transition-transform duration-200"
                    loading="lazy"
                  />
                </div>
              ) : null;
            })()}
            <div className="p-4">
              <h3 className="font-semibold text-gray-900 group-hover:text-blue-600 transition-colors mb-2 line-clamp-2">
                {post.title}
              </h3>
              <div className="text-sm text-gray-600 line-clamp-2 mb-2">
                <ContentRenderer content={post.excerptHtml} />
              </div>
              <span className="text-xs text-blue-600 font-medium">
                {t('blog.readMore', locale as 'en' | 'de')} →
              </span>
            </div>
          </Link>
        ))}
      </div>
    </div>
  );
}

export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
  const locale = (params.locale as string) || 'en';
  const post = getPostBySlug(params.slug, locale as 'en' | 'de');
  
  if (!post) {
    return {
      title: 'Post not found',
    };
  }

  const site = getSiteInfo();
  
  // Get featured image URL if available
  let featuredImageUrl: string | undefined;
  if (post.featuredImage) {
    const media = getMediaById(post.featuredImage);
    if (media) {
      featuredImageUrl = media.localPath;
    }
  }
  
  return {
    title: `${post.title} | ${site.title}`,
    description: post.excerptHtml || undefined,
    alternates: {
      canonical: getLocalizedPath(`/blog/${post.slug}`, locale as 'en' | 'de'),
      languages: {
        'en': `/en/blog/${post.slug}`,
        'de': `/de/blog/${post.slug}`,
      },
    },
    openGraph: {
      title: post.title,
      description: post.excerptHtml || undefined,
      type: 'article',
      locale,
      publishedTime: post.datePublished,
      modifiedTime: post.updatedAt,
      ...(featuredImageUrl && {
        images: [{ url: featuredImageUrl, alt: post.title }],
      }),
    },
  };
}

export async function generateStaticParams() {
  const postsEN = getPostsByLocale('en');
  const postsDE = getPostsByLocale('de');
  
  const enParams = postsEN.map((post: any) => ({
    slug: post.slug,
    locale: 'en',
  }));
  
  const deParams = postsDE.map((post: any) => ({
    slug: post.slug,
    locale: 'de',
  }));
  
  return [...enParams, ...deParams];
}

export default async function BlogDetailPage({ params }: PageProps) {
  const locale = (params.locale as string) || 'en';
  const post = getPostBySlug(params.slug, locale as 'en' | 'de');
  
  if (!post) {
    notFound();
  }

  // Content is already processed during data export

  return (
    <>
      <SEO
        title={post.title}
        description={post.excerptHtml}
        locale={locale as 'en' | 'de'}
        path={`/blog/${post.slug}`}
        type="article"
        publishedTime={post.datePublished}
        modifiedTime={post.updatedAt}
        images={post.featuredImage ? [getMediaById(post.featuredImage)?.localPath].filter(Boolean) : undefined}
      />
        
      <article className="bg-white py-12 sm:py-20">
        <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
          {/* Back to blog link */}
          <div className="mb-8">
            <Link
              href={getLocalizedPath('/blog', locale as 'en' | 'de')}
              className="inline-flex items-center text-sm text-gray-600 hover:text-gray-900 transition-colors"
            >
              <svg className="mr-2 h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
              </svg>
              {t('blog.backToBlog', locale as 'en' | 'de')}
            </Link>
          </div>

          {/* Article Header */}
          <header className="mb-10">
            <div className="flex items-center gap-2 mb-4">
              <time className="text-sm text-gray-500">
                {new Date(post.datePublished).toLocaleDateString(locale as 'en' | 'de', {
                  year: 'numeric',
                  month: 'long',
                  day: 'numeric',
                })}
              </time>
            </div>
            
            <h1 className="text-4xl sm:text-5xl font-bold text-gray-900 mb-6 leading-tight">
              {post.title}
            </h1>
            
            {post.excerptHtml && (
              <p className="text-xl text-gray-600 leading-relaxed">
                <ContentRenderer content={post.excerptHtml} />
              </p>
            )}
          </header>

          {/* Featured Image */}
          {post.featuredImage && (() => {
            const media = getMediaById(post.featuredImage);
            return media ? (
              <div className="mb-12 rounded-2xl overflow-hidden bg-gray-100">
                <img
                  src={media.localPath}
                  alt={post.title}
                  className="w-full h-auto object-cover"
                  loading="eager"
                />
              </div>
            ) : null;
          })()}

          {/* Article Content */}
         <div className="mb-12">
           <ContentRenderer
             content={post.contentHtml}
             className="prose prose-lg prose-blue"
             parsePatterns={true}
           />
         </div>

          {/* Article Footer */}
          <footer className="border-t border-gray-200 pt-8 mt-12">
            <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
              <div className="flex gap-4">
                <Link
                  href={getLocalizedPath('/blog', locale as 'en' | 'de')}
                  className="inline-flex items-center px-4 py-2 border border-gray-300 rounded-md text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 transition-colors"
                >
                  {t('blog.backToList', locale as 'en' | 'de')}
                </Link>
                <Link
                  href={getLocalizedPath('/contact', locale as 'en' | 'de')}
                  className="inline-flex items-center px-4 py-2 border border-transparent rounded-md text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 transition-colors"
                >
                  {t('nav.contact', locale as 'en' | 'de')}
                </Link>
              </div>
            </div>
          </footer>

          {/* Related Posts */}
          <RelatedPosts currentSlug={params.slug} locale={locale as 'en' | 'de'} />
        </div>
      </article>

      {/* Locale Switcher */}
      <div className="bg-gray-50 py-8">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 text-center">
          <LocaleSwitcher />
        </div>
      </div>
    </>
  );
}