import { setRequestLocale } from 'next-intl/server';
import { getTranslations } from 'next-intl/server';
import { ArrowRight, Calendar, Tag, ExternalLink, ChevronLeft, ChevronRight } from 'lucide-react';
import Link from 'next/link';
import Image from 'next/image';
import type { Metadata } from 'next';
import { getAllBlogPosts, BlogPost } from '@/lib/blog';
import { legacyBlogPosts } from '@/data/legacyBlogPosts';

const POSTS_PER_PAGE = 12;

type Props = {
  params: Promise<{ locale: string }>;
  searchParams: Promise<{ page?: string }>;
};

const BASE_URL = process.env.NEXT_PUBLIC_SITE_URL || 'https://damjan-savic.com';

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { locale } = await params;
  const t = await getTranslations({ locale, namespace: 'blog.meta' });

  const keywords: Record<string, string[]> = {
    de: [
      'KI Blog',
      'Automatisierung Blog',
      'Tech Blog',
      'KI-Agenten',
      'n8n Tutorials',
      'Voice AI',
      'SaaS Entwicklung',
      'Python Tutorials',
    ],
    en: [
      'AI Blog',
      'Automation Blog',
      'Tech Blog',
      'AI Agents Guide',
      'n8n Tutorials',
      'Voice AI Guide',
      'SaaS Development',
      'Python Tutorials',
      'GPT-4 Integration Guide',
      'AI Developer Blog',
      'Process Automation Tips',
    ],
    sr: [
      'AI Blog',
      'Automatizacija Blog',
      'Tech Blog',
      'AI Agenti',
      'n8n Tutoriali',
      'Voice AI',
      'SaaS Razvoj',
      'Python Tutoriali',
    ],
  };

  const localePath = locale === 'de' ? '/blog' : `/${locale}/blog`;

  return {
    title: t('title'),
    description: t('description'),
    keywords: keywords[locale] || keywords.de,
    alternates: {
      canonical: `${BASE_URL}${localePath}`,
      languages: {
        'x-default': `${BASE_URL}/blog`,
        de: `${BASE_URL}/blog`,
        en: `${BASE_URL}/en/blog`,
        sr: `${BASE_URL}/sr/blog`,
      },
    },
    openGraph: {
      title: t('title'),
      description: t('description'),
      url: `${BASE_URL}${localePath}`,
      type: 'website',
      locale: locale === 'de' ? 'de_DE' : locale === 'sr' ? 'sr_RS' : 'en_US',
      alternateLocale: ['de_DE', 'en_US', 'sr_RS'].filter(l => l !== (locale === 'de' ? 'de_DE' : locale === 'sr' ? 'sr_RS' : 'en_US')),
    },
  };
}

function getFormattedDate(date: string, locale: string) {
  const languageMap: Record<string, string> = {
    de: 'de-DE',
    en: 'en-US',
    sr: 'sr-RS',
  };

  return new Date(date).toLocaleDateString(languageMap[locale] || 'de-DE', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
  });
}

function getImagePath(coverImage: string) {
  if (coverImage.startsWith('http')) {
    return coverImage;
  }
  return coverImage.replace('/blog/', '/images/posts/');
}

// Known existing images (from public/images/posts/)
const EXISTING_IMAGES = new Set([
  '/images/posts/erp-integration-breuninger/cover.jpg',
  '/images/posts/fullstack-development-timetracking/cover.jpg',
  '/images/posts/rfid-automation/cover.jpg',
  '/images/posts/automated-ad-creatives/cover.jpg',
]);

// Blog image component
function BlogImage({ src, alt }: { src: string; alt: string }) {
  return (
    <Image
      src={src}
      alt={alt}
      fill
      sizes="(max-width: 640px) 350px, (max-width: 768px) 400px, (max-width: 1024px) 550px, 400px"
      className="object-cover transition-transform duration-700 group-hover:scale-110"
    />
  );
}

function BlogPostCard({ post, locale }: { post: BlogPost; locale: string }) {
  return (
    <Link
      href={`/${locale}/blog/${post.slug}`}
      className="group relative block bg-zinc-900/50 backdrop-blur-sm
               rounded-xl shadow-lg hover:shadow-2xl
               ring-1 ring-zinc-800 hover:ring-zinc-700
               transition-all duration-500 focus:outline-none focus:ring-2
               focus:ring-zinc-600 focus:ring-offset-2 focus:ring-offset-zinc-950
               transform hover:-translate-y-1"
    >
      <div className="relative overflow-hidden rounded-xl">
        {/* Image Container */}
        <div className="aspect-[16/9] w-full relative overflow-hidden bg-zinc-900">
          <BlogImage
            src={getImagePath(post.coverImage)}
            alt={post.title}
          />
          <div className="absolute inset-x-0 -bottom-20 top-0 bg-gradient-to-t from-zinc-900 via-zinc-900/70 to-transparent opacity-95" />
        </div>

        {/* Content */}
        <div className="relative -mt-2 p-6 bg-zinc-900 z-10">
          <div className="flex items-center gap-4 mb-4 text-zinc-500">
            <div className="flex items-center gap-2 text-sm">
              <Calendar className="h-4 w-4" />
              <span>{getFormattedDate(post.date, locale)}</span>
            </div>
            {post.tags && post.tags.length > 0 && (
              <div className="flex items-center gap-2 text-sm">
                <Tag className="h-4 w-4" />
                <span>{post.tags.length} Tags</span>
              </div>
            )}
          </div>

          <h3 className="text-xl font-semibold text-white mb-3
                       group-hover:text-zinc-100 transition-colors duration-300">
            {post.title}
          </h3>
          <p className="text-zinc-400 text-sm line-clamp-2 mb-4
                      group-hover:text-zinc-300 transition-colors duration-300">
            {post.excerpt}
          </p>

          {/* Tags */}
          <div className="flex flex-wrap gap-2">
            {post.tags?.slice(0, 3).map((tag, index) => (
              <span
                key={index}
                className="px-3 py-1 bg-zinc-800/50
                         text-sm text-zinc-400 rounded-full
                         ring-1 ring-zinc-700/50 group-hover:ring-zinc-600/50
                         group-hover:bg-zinc-800/70 group-hover:text-zinc-300
                         transition-all duration-300"
              >
                {tag}
              </span>
            ))}
            {post.tags && post.tags.length > 3 && (
              <span className="text-sm text-zinc-600">
                +{post.tags.length - 3} more
              </span>
            )}
          </div>

          {/* Link Icon */}
          <div className="absolute top-6 right-6 p-2.5 rounded-full
                        bg-zinc-800/60 backdrop-blur-sm ring-1 ring-zinc-700/50
                        opacity-0 group-hover:opacity-100
                        transform translate-y-2 group-hover:translate-y-0
                        transition-all duration-300">
            <ExternalLink className="h-4 w-4 text-zinc-400" />
          </div>
        </div>
      </div>
    </Link>
  );
}

// Pagination component
function Pagination({
  currentPage,
  totalPages,
  locale,
  t,
}: {
  currentPage: number;
  totalPages: number;
  locale: string;
  t: (key: string) => string;
}) {
  const getPageNumbers = () => {
    const pages: (number | 'ellipsis')[] = [];

    if (totalPages <= 7) {
      // Show all pages if 7 or fewer
      for (let i = 1; i <= totalPages; i++) {
        pages.push(i);
      }
    } else {
      // Always show first page
      pages.push(1);

      if (currentPage > 3) {
        pages.push('ellipsis');
      }

      // Show pages around current
      const start = Math.max(2, currentPage - 1);
      const end = Math.min(totalPages - 1, currentPage + 1);

      for (let i = start; i <= end; i++) {
        pages.push(i);
      }

      if (currentPage < totalPages - 2) {
        pages.push('ellipsis');
      }

      // Always show last page
      pages.push(totalPages);
    }

    return pages;
  };

  if (totalPages <= 1) return null;

  return (
    <nav className="flex items-center justify-center gap-2 mt-12 sm:mt-16" aria-label="Pagination">
      {/* Previous button */}
      {currentPage > 1 ? (
        <Link
          href={`/${locale}/blog${currentPage > 2 ? `?page=${currentPage - 1}` : ''}`}
          className="flex items-center gap-1 px-3 py-2 text-sm text-zinc-400 hover:text-white
                     bg-zinc-800/50 hover:bg-zinc-800 rounded-lg ring-1 ring-zinc-700/50
                     hover:ring-zinc-600 transition-all duration-200"
          aria-label={t('ui.pagination.previous')}
        >
          <ChevronLeft className="h-4 w-4" />
          <span className="hidden sm:inline">{t('ui.pagination.previous')}</span>
        </Link>
      ) : (
        <span
          className="flex items-center gap-1 px-3 py-2 text-sm text-zinc-600
                     bg-zinc-800/30 rounded-lg ring-1 ring-zinc-800/50 cursor-not-allowed"
          aria-disabled="true"
        >
          <ChevronLeft className="h-4 w-4" />
          <span className="hidden sm:inline">{t('ui.pagination.previous')}</span>
        </span>
      )}

      {/* Page numbers */}
      <div className="flex items-center gap-1">
        {getPageNumbers().map((page, index) => {
          if (page === 'ellipsis') {
            return (
              <span key={`ellipsis-${index}`} className="px-2 text-zinc-600">
                ...
              </span>
            );
          }

          const isCurrentPage = page === currentPage;

          return (
            <Link
              key={page}
              href={`/${locale}/blog${page > 1 ? `?page=${page}` : ''}`}
              className={`min-w-[40px] h-10 flex items-center justify-center text-sm rounded-lg
                         ring-1 transition-all duration-200
                         ${isCurrentPage
                           ? 'bg-[#697565] text-white ring-[#697565] font-medium'
                           : 'text-zinc-400 hover:text-white bg-zinc-800/50 hover:bg-zinc-800 ring-zinc-700/50 hover:ring-zinc-600'
                         }`}
              aria-current={isCurrentPage ? 'page' : undefined}
            >
              {page}
            </Link>
          );
        })}
      </div>

      {/* Next button */}
      {currentPage < totalPages ? (
        <Link
          href={`/${locale}/blog?page=${currentPage + 1}`}
          className="flex items-center gap-1 px-3 py-2 text-sm text-zinc-400 hover:text-white
                     bg-zinc-800/50 hover:bg-zinc-800 rounded-lg ring-1 ring-zinc-700/50
                     hover:ring-zinc-600 transition-all duration-200"
          aria-label={t('ui.pagination.next')}
        >
          <span className="hidden sm:inline">{t('ui.pagination.next')}</span>
          <ChevronRight className="h-4 w-4" />
        </Link>
      ) : (
        <span
          className="flex items-center gap-1 px-3 py-2 text-sm text-zinc-600
                     bg-zinc-800/30 rounded-lg ring-1 ring-zinc-800/50 cursor-not-allowed"
          aria-disabled="true"
        >
          <span className="hidden sm:inline">{t('ui.pagination.next')}</span>
          <ChevronRight className="h-4 w-4" />
        </span>
      )}
    </nav>
  );
}

export default async function BlogPage({ params, searchParams }: Props) {
  const { locale } = await params;
  const { page } = await searchParams;
  setRequestLocale(locale);

  const t = await getTranslations('blog');

  // Get dynamic posts from markdown files
  const dynamicPosts = getAllBlogPosts();

  // Get legacy posts (with translations)
  const legacyPosts = legacyBlogPosts[locale] || legacyBlogPosts.de;

  // Merge: dynamic posts first, then legacy posts (avoiding duplicates)
  const legacySlugs = new Set(legacyPosts.map(p => p.slug));
  const allPosts = [
    ...dynamicPosts.filter(p => !legacySlugs.has(p.slug)),
    ...legacyPosts,
  ].sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());

  // Pagination
  const currentPage = Math.max(1, parseInt(page || '1', 10) || 1);
  const totalPages = Math.ceil(allPosts.length / POSTS_PER_PAGE);
  const validPage = Math.min(currentPage, totalPages || 1);

  const startIndex = (validPage - 1) * POSTS_PER_PAGE;
  const endIndex = startIndex + POSTS_PER_PAGE;
  const posts = allPosts.slice(startIndex, endIndex);

  return (
    <main className="min-h-screen">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-16 sm:py-20 lg:py-24">
        {/* Header Section */}
        <div className="mb-12 sm:mb-16 lg:mb-20">
          <div className="flex items-center gap-4 mb-8">
            <ArrowRight className="h-5 w-5 text-zinc-500" />
            <h2 className="text-white text-sm tracking-wider">BLOG</h2>
          </div>
          <h1 className="text-3xl sm:text-4xl lg:text-5xl font-bold text-white mb-6">
            {t('meta.header.title')}
          </h1>
          <p className="text-lg sm:text-xl text-zinc-400 max-w-2xl">
            {t('meta.header.subtitle')}
          </p>
          {/* Post count */}
          <p className="text-sm text-zinc-500 mt-4">
            {t('ui.pagination.showing', {
              start: startIndex + 1,
              end: Math.min(endIndex, allPosts.length),
              total: allPosts.length,
            })}
          </p>
        </div>

        {/* Blog Posts Grid */}
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6 sm:gap-8">
          {posts.map((post) => (
            <BlogPostCard key={post.slug} post={post} locale={locale} />
          ))}
        </div>

        {/* Pagination */}
        <Pagination
          currentPage={validPage}
          totalPages={totalPages}
          locale={locale}
          t={(key) => t(key)}
        />

        {/* Empty State */}
        {posts.length === 0 && (
          <div className="text-center py-12">
            <p className="text-zinc-400">{t('ui.errors.posts')}</p>
          </div>
        )}
      </div>
    </main>
  );
}
