import Link from 'next/link';
import Image from 'next/image';
import { getAllPosts } from '@/lib/blog';
import { Section, Container, Heading, Card, Badge, Button } from '@/components/ui';
import Reveal from '@/components/Reveal';
import { Metadata } from 'next';
import { getTranslations, setRequestLocale } from 'next-intl/server';
import { SITE_URL } from '@/lib/schema';
import { BlogPaginationKeyboardObserver } from '@/components/blog/BlogPaginationKeyboardObserver';

interface BlogIndexProps {
  params: Promise<{
    locale: string;
  }>;
}

export async function generateMetadata({ params }: BlogIndexProps) {
  const { locale } = await params;
  const t = await getTranslations({ locale, namespace: 'Blog.meta' });
  return {
    title: t('title'),
    description: t('description'),
    alternates: {
      canonical: `${SITE_URL}/${locale}/blog`,
      languages: {
        de: `${SITE_URL}/de/blog`,
        en: `${SITE_URL}/en/blog`,
        'x-default': `${SITE_URL}/en/blog`,
      },
    },
    openGraph: {
      title: `${t('title')} | KLZ Cables`,
      description: t('description'),
      url: `${SITE_URL}/${locale}/blog`,
    },
    twitter: {
      card: 'summary_large_image',
      title: `${t('title')} | KLZ Cables`,
      description: t('description'),
    },
  };
}

export default async function BlogIndex({ params }: BlogIndexProps) {
  const { locale } = await params;
  setRequestLocale(locale);
  const t = await getTranslations('Blog');
  const posts = await getAllPosts(locale);

  // Sort posts by date descending
  const sortedPosts = [...posts].sort(
    (a, b) => new Date(b.frontmatter.date).getTime() - new Date(a.frontmatter.date).getTime(),
  );

  const featuredPost = sortedPosts[0];
  const remainingPosts = sortedPosts.slice(1);

  return (
    <div className="bg-neutral-light min-h-screen">
      {/* Hero Section - Immersive Magazine Feel */}
      <Reveal>
        <article className="relative h-[50vh] md:h-[70vh] min-h-[400px] md:min-h-[600px] flex items-center overflow-hidden bg-primary-dark">
          {featuredPost && featuredPost.frontmatter.featuredImage && (
            <>
              <Image
                src={featuredPost.frontmatter.featuredImage.split('?')[0]}
                alt={featuredPost.frontmatter.title}
                fill
                className="absolute inset-0 w-full h-full object-cover opacity-40 md:opacity-60"
                sizes="100vw"
                priority
              />
              <div className="absolute inset-0 image-overlay-gradient" />
            </>
          )}

          <Container className="relative z-10">
            <div className="max-w-4xl">
              <div className="flex flex-wrap items-center gap-3 mb-4 md:mb-6">
                <Badge variant="saturated">{t('featuredPost')}</Badge>
                {featuredPost &&
                  (new Date(featuredPost.frontmatter.date) > new Date() ||
                    featuredPost.frontmatter.public === false) && (
                    <Badge
                      variant="neutral"
                      className="border border-white/30 bg-transparent text-white/80 shadow-none"
                    >
                      Draft Preview
                    </Badge>
                  )}
              </div>
              {featuredPost && (
                <>
                  <Heading level={1} className="text-white mb-4 md:mb-8">
                    {featuredPost.frontmatter.title}
                  </Heading>
                  <p className="text-base md:text-xl text-white/80 mb-6 md:mb-10 line-clamp-3 md:line-clamp-4 max-w-2xl">
                    {featuredPost.frontmatter.excerpt}
                  </p>
                  <Button
                    href={`/${locale}/blog/${featuredPost.slug}`}
                    variant="accent"
                    size="lg"
                    className="group w-full md:w-auto md:h-16 md:px-10 md:text-xl"
                  >
                    {t('readFullArticle')}
                    <span className="ml-3 transition-transform group-hover:translate-x-2">
                      &rarr;
                    </span>
                  </Button>
                </>
              )}
            </div>
          </Container>
        </article>
      </Reveal>

      <Section className="bg-neutral-light py-12 md:py-28">
        <Container>
          <Reveal>
            <div className="flex flex-col md:flex-row items-start md:items-end justify-between mb-8 md:mb-16 gap-4 md:gap-6">
              <Heading level={2} subtitle={t('latestNews')} className="mb-0">
                {t('allArticles')}
              </Heading>
              <div className="flex flex-wrap gap-2 md:gap-4">
                {/* Category filters could go here */}
                <Badge
                  variant="primary"
                  className="cursor-pointer hover:bg-primary hover:text-white transition-colors touch-target px-3 md:px-4"
                >
                  {t('categories.all')}
                </Badge>
                <Badge
                  variant="neutral"
                  className="cursor-pointer hover:bg-primary hover:text-white transition-colors touch-target px-3 md:px-4"
                >
                  {t('categories.industry')}
                </Badge>
                <Badge
                  variant="neutral"
                  className="cursor-pointer hover:bg-primary hover:text-white transition-colors touch-target px-3 md:px-4"
                >
                  {t('categories.technical')}
                </Badge>
                <Badge
                  variant="neutral"
                  className="cursor-pointer hover:bg-primary hover:text-white transition-colors touch-target px-3 md:px-4"
                >
                  {t('categories.sustainability')}
                </Badge>
              </div>
            </div>
          </Reveal>

          {/* Grid for remaining posts */}
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 md:gap-12">
            {remainingPosts.map((post, idx) => (
              <Reveal key={post.slug} delay={idx * 100}>
                <Link href={`/${locale}/blog/${post.slug}`} className="group block">
                  <Card
                    tag="article"
                    className="h-full flex flex-col border-none shadow-lg hover:shadow-2xl transition-all duration-500 rounded-2xl md:rounded-3xl overflow-hidden"
                  >
                    {post.frontmatter.featuredImage && (
                      <div className="relative h-48 md:h-72 overflow-hidden">
                        <Image
                          src={post.frontmatter.featuredImage.split('?')[0]}
                          alt={post.frontmatter.title}
                          fill
                          className="w-full h-full object-cover transition-transform duration-1000 group-hover:scale-110"
                          sizes="(max-width: 768px) 100vw, (max-width: 1024px) 50vw, 33vw"
                        />
                        <div className="absolute inset-0 image-overlay-gradient opacity-0 group-hover:opacity-100 transition-opacity duration-500" />
                        {post.frontmatter.category && (
                          <Badge
                            variant="accent"
                            className="absolute top-3 left-3 md:top-6 md:left-6 shadow-lg"
                          >
                            {post.frontmatter.category}
                          </Badge>
                        )}
                      </div>
                    )}
                    <div className="p-5 md:p-10 flex flex-col flex-1">
                      <div className="flex items-center gap-3 text-[10px] md:text-sm font-bold text-primary/70 mb-2 md:mb-4 tracking-widest uppercase">
                        <span>
                          {new Date(post.frontmatter.date).toLocaleDateString(locale, {
                            year: 'numeric',
                            month: 'long',
                            day: 'numeric',
                          })}
                        </span>
                        {(new Date(post.frontmatter.date) > new Date() ||
                          post.frontmatter.public === false) && (
                          <span className="px-1.5 py-0.5 border border-current rounded-sm text-[9px] md:text-xs">
                            Draft
                          </span>
                        )}
                      </div>
                      <h3 className="text-lg md:text-2xl font-bold text-primary mb-3 md:mb-6 group-hover:text-accent-dark transition-colors line-clamp-3 md:line-clamp-4 leading-tight">
                        {post.frontmatter.title}
                      </h3>
                      <p className="text-text-secondary text-sm md:text-lg line-clamp-3 md:line-clamp-4 mb-4 md:mb-8 leading-relaxed">
                        {post.frontmatter.excerpt}
                      </p>
                      <div className="mt-auto pt-4 md:pt-8 border-t border-neutral-medium flex items-center justify-between">
                        <span className="text-saturated text-sm md:text-base font-extrabold group-hover:text-accent-dark transition-colors">
                          {t('readMore')}
                        </span>
                        <div className="w-8 h-8 md:w-10 md:h-10 rounded-full bg-primary-light flex items-center justify-center text-saturated group-hover:bg-accent group-hover:text-primary-dark transition-all duration-300">
                          <svg
                            className="w-4 h-4 md:w-5 md:h-5 transition-transform group-hover:translate-x-1"
                            fill="none"
                            stroke="currentColor"
                            viewBox="0 0 24 24"
                          >
                            <path
                              strokeLinecap="round"
                              strokeLinejoin="round"
                              strokeWidth={2}
                              d="M17 8l4 4m0 0l-4 4m4-4H3"
                            />
                          </svg>
                        </div>
                      </div>
                    </div>
                  </Card>
                </Link>
              </Reveal>
            ))}
          </div>

          {/* Pagination */}
          <div className="mt-12 md:mt-24 flex justify-center gap-2 md:gap-4">
            <Button
              href="#"
              variant="outline"
              size="sm"
              className="md:h-11 md:px-6 md:text-base pointer-events-none opacity-50"
              aria-disabled="true"
              aria-keyshortcuts="ArrowLeft"
              tabIndex={-1}
            >
              {t('prev')}
            </Button>
            <Button
              href={`/${locale}/blog?page=1`}
              variant="primary"
              size="sm"
              className="md:h-11 md:px-6 md:text-base"
              aria-current="page"
            >
              1
            </Button>
            <Button
              href={`/${locale}/blog?page=2`}
              variant="outline"
              size="sm"
              className="md:h-11 md:px-6 md:text-base"
            >
              2
            </Button>
            <Button
              href={`/${locale}/blog?page=2`}
              variant="outline"
              size="sm"
              className="md:h-11 md:px-6 md:text-base"
              aria-keyshortcuts="ArrowRight"
            >
              {t('next')}
            </Button>
          </div>
          <BlogPaginationKeyboardObserver currentPage={1} totalPages={2} locale={locale} />
        </Container>
      </Section>
    </div>
  );
}
