import { Metadata } from 'next';
import Link from 'next/link';
import { getPostsByLocale, getCategoriesByLocale, getMediaById } from '@/lib/data';
import { getSiteInfo, t, getLocalizedPath } from '@/lib/i18n';
import { SEO } from '@/components/SEO';
import { LocaleSwitcher } from '@/components/LocaleSwitcher';
import { processHTML } from '@/lib/html-compat';

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

export async function generateStaticParams() {
  return [
    { locale: 'en' },
    { locale: 'de' },
  ];
}

export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
  const locale = (params?.locale as string) || 'en';
  const site = getSiteInfo();
  const title = t('blog.title', locale as 'en' | 'de');
  const description = t('blog.description', locale as 'en' | 'de');
  
  return {
    title: `${title} | ${site.title}`,
    description,
    alternates: {
      canonical: getLocalizedPath('/blog', locale as 'en' | 'de'),
      languages: {
        'en': '/en/blog',
        'de': '/de/blog',
      },
    },
    openGraph: {
      title: `${title} | ${site.title}`,
      description,
      type: 'website',
      locale,
    },
  };
}

export default async function BlogPage({ params }: PageProps) {
  const locale = (params?.locale as string) || 'en';
  const posts = getPostsByLocale(locale as 'en' | 'de');
  const categories = getCategoriesByLocale(locale as 'en' | 'de');
  
  const title = t('blog.title', locale as 'en' | 'de');
  const description = t('blog.description', locale as 'en' | 'de');

  // Get featured posts (first 3)
  const featuredPosts = posts.slice(0, 3);
  // Get remaining posts
  const remainingPosts = posts.slice(3);

  return (
    <>
      <SEO 
        title={title}
        description={description}
        locale={locale as 'en' | 'de'}
        path="/blog"
      />
      
      <div className="bg-white py-24 sm:py-32">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="max-w-2xl">
            <h1 className="text-4xl font-bold tracking-tight text-gray-900 sm:text-5xl mb-6">
              {title}
            </h1>
            <p className="text-xl text-gray-600 mb-8">
              {description}
            </p>
          </div>

          {/* Categories */}
          {categories.length > 0 && (
            <div className="mb-12">
              <h2 className="text-sm font-semibold text-gray-500 uppercase tracking-wider mb-4">
                {t('blog.categories', locale as 'en' | 'de')}
              </h2>
              <div className="flex flex-wrap gap-2">
                {categories.map((category) => (
                  <Link
                    key={category.slug}
                    href={getLocalizedPath(`/blog/category/${category.slug}`, locale as 'en' | 'de')}
                    className="inline-flex items-center px-3 py-1.5 rounded-full text-sm font-medium bg-blue-50 text-blue-700 hover:bg-blue-100 transition-colors"
                  >
                    {category.name}
                  </Link>
                ))}
              </div>
            </div>
          )}

          {/* Featured Posts */}
          {featuredPosts.length > 0 && (
            <div className="mb-16">
              <h2 className="text-2xl font-bold text-gray-900 mb-6">
                {t('blog.featured', locale as 'en' | 'de')}
              </h2>
              <div className="grid gap-8 md:grid-cols-2 lg:grid-cols-3">
                {featuredPosts.map((post) => (
                  <article
                    key={post.slug}
                    className="flex flex-col bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden hover:shadow-md transition-shadow"
                  >
                    {post.featuredImage && (() => {
                      const media = getMediaById(post.featuredImage);
                      return media ? (
                        <div className="h-48 overflow-hidden bg-gray-100">
                          <img
                            src={media.localPath}
                            alt={post.title}
                            className="h-full w-full object-cover"
                            loading="lazy"
                          />
                        </div>
                      ) : null;
                    })()}
                    <div className="flex-1 p-6">
                      <div className="flex items-center gap-2 mb-3">
                        <time className="text-xs text-gray-500">
                          {new Date(post.datePublished).toLocaleDateString(locale, {
                            year: 'numeric',
                            month: 'short',
                            day: 'numeric',
                          })}
                        </time>
                      </div>
                      <h3 className="text-lg font-semibold text-gray-900 mb-2">
                        <Link
                          href={getLocalizedPath(`/blog/${post.slug}`, locale as 'en' | 'de')}
                          className="hover:text-blue-600 transition-colors"
                        >
                          {post.title}
                        </Link>
                      </h3>
                      <div 
                        className="text-gray-600 line-clamp-3 text-sm mb-4"
                        dangerouslySetInnerHTML={{ __html: processHTML(post.excerptHtml) }}
                      />
                      <Link
                        href={getLocalizedPath(`/blog/${post.slug}`, locale as 'en' | 'de')}
                        className="inline-flex items-center text-sm font-medium text-blue-600 hover:text-blue-700"
                      >
                        {t('blog.readMore', locale as 'en' | 'de')}
                        <svg className="ml-1 h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                        </svg>
                      </Link>
                    </div>
                  </article>
                ))}
              </div>
            </div>
          )}

          {/* All Posts */}
          {remainingPosts.length > 0 && (
            <div>
              <h2 className="text-2xl font-bold text-gray-900 mb-6">
                {t('blog.allPosts', locale as 'en' | 'de')}
              </h2>
              <div className="space-y-8">
                {remainingPosts.map((post) => (
                  <article
                    key={post.slug}
                    className="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden hover:shadow-md transition-shadow"
                  >
                    <div className="p-6">
                      <div className="flex items-center gap-2 mb-3">
                        <time className="text-xs text-gray-500">
                          {new Date(post.datePublished).toLocaleDateString(locale, {
                            year: 'numeric',
                            month: 'short',
                            day: 'numeric',
                          })}
                        </time>
                      </div>
                      <div className="flex gap-6">
                        {post.featuredImage && (() => {
                          const media = getMediaById(post.featuredImage);
                          return media ? (
                            <div className="w-32 h-32 flex-shrink-0 bg-gray-100 rounded-lg overflow-hidden">
                              <img
                                src={media.localPath}
                                alt={post.title}
                                className="h-full w-full object-cover"
                                loading="lazy"
                              />
                            </div>
                          ) : null;
                        })()}
                        <div className="flex-1">
                          <h3 className="text-xl font-semibold text-gray-900 mb-2">
                            <Link
                              href={getLocalizedPath(`/blog/${post.slug}`, locale as 'en' | 'de')}
                              className="hover:text-blue-600 transition-colors"
                            >
                              {post.title}
                            </Link>
                          </h3>
                          <div 
                            className="text-gray-600 mb-3"
                            dangerouslySetInnerHTML={{ __html: processHTML(post.excerptHtml) }}
                          />
                          <Link
                            href={getLocalizedPath(`/blog/${post.slug}`, locale as 'en' | 'de')}
                            className="inline-flex items-center text-sm font-medium text-blue-600 hover:text-blue-700"
                          >
                            {t('blog.readMore', locale as 'en' | 'de')}
                            <svg className="ml-1 h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                            </svg>
                          </Link>
                        </div>
                      </div>
                    </div>
                  </article>
                ))}
              </div>
            </div>
          )}

          {/* Empty State */}
          {posts.length === 0 && (
            <div className="text-center py-16">
              <div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-gray-100 mb-4">
                <svg className="w-8 h-8 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                </svg>
              </div>
              <h3 className="text-lg font-semibold text-gray-900 mb-2">
                {t('blog.noPosts', locale as 'en' | 'de')}
              </h3>
              <p className="text-gray-600">
                {t('blog.noPostsDescription', locale as 'en' | 'de')}
              </p>
            </div>
          )}
        </div>
      </div>

      {/* 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>
    </>
  );
}