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;
  }>;
  searchParams: Promise<{ [key: string]: string | string[] | undefined }>;
}

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, searchParams }: BlogIndexProps) {
  const { locale } = await params;
  const resolvedSearchParams = await searchParams;
  const categoryParam = resolvedSearchParams.category as string | undefined;
  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 filteredPosts = categoryParam
    ? sortedPosts.filter(
        (post) => post.frontmatter.category?.toLowerCase() === categoryParam.toLowerCase(),
      )
    : sortedPosts;

  const featuredPost = filteredPosts[0];
  const remainingPosts = filteredPosts.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"
                style={{
                  objectPosition: `${featuredPost.frontmatter.focalX ?? 50}% ${featuredPost.frontmatter.focalY ?? 50}%`,
                }}
                sizes="100vw"
                priority
              />
              <div className="absolute inset-0 bg-neutral-dark/20" />
            </>
          )}

          <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) && (
                    <span className="px-2 py-0.5 border border-white/40 text-white/80 rounded uppercase tracking-widest text-[10px] md:text-xs font-bold">
                      Draft Preview
                    </span>
                  )}
              </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">
                <Link href={`/${locale}/blog`}>
                  <Badge
                    variant={!categoryParam ? 'primary' : 'neutral'}
                    className="cursor-pointer hover:bg-primary hover:text-white transition-colors touch-target px-3 md:px-4"
                  >
                    {t('categories.all')}
                  </Badge>
                </Link>
                <Link href={`/${locale}/blog?category=industry`}>
                  <Badge
                    variant={categoryParam === 'industry' ? 'primary' : 'neutral'}
                    className="cursor-pointer hover:bg-primary hover:text-white transition-colors touch-target px-3 md:px-4"
                  >
                    {t('categories.industry')}
                  </Badge>
                </Link>
                <Link href={`/${locale}/blog?category=technical`}>
                  <Badge
                    variant={categoryParam === 'technical' ? 'primary' : 'neutral'}
                    className="cursor-pointer hover:bg-primary hover:text-white transition-colors touch-target px-3 md:px-4"
                  >
                    {t('categories.technical')}
                  </Badge>
                </Link>
                <Link href={`/${locale}/blog?category=sustainability`}>
                  <Badge
                    variant={categoryParam === 'sustainability' ? 'primary' : 'neutral'}
                    className="cursor-pointer hover:bg-primary hover:text-white transition-colors touch-target px-3 md:px-4"
                  >
                    {t('categories.sustainability')}
                  </Badge>
                </Link>
              </div>
            </div>
          </Reveal>

          {/* Grid for remaining posts */}
          <div className="grid grid-cols-1 gap-12">
            {remainingPosts.map((post, idx) => (
              <Reveal key={post.slug} delay={idx * 50}>
                <Link
                  href={`/${locale}/blog/${post.slug}`}
                  className="group block focus:outline-none"
                >
                  <Card
                    tag="article"
                    className="relative flex flex-col justify-end border-none shadow-lg hover:shadow-2xl transition-all duration-500 rounded-3xl overflow-hidden min-h-[450px] md:min-h-[500px]"
                  >
                    {post.frontmatter.featuredImage && (
                      <>
                        <Image
                          src={post.frontmatter.featuredImage.split('?')[0]}
                          alt={post.frontmatter.title}
                          fill
                          className="absolute inset-0 w-full h-full object-cover transition-transform duration-1000 group-hover:scale-105"
                          style={{
                            objectPosition: `${post.frontmatter.focalX ?? 50}% ${post.frontmatter.focalY ?? 50}%`,
                          }}
                          sizes="(max-width: 768px) 100vw, 100vw"
                          loading="lazy"
                        />
                        <div className="absolute inset-0 bg-neutral-dark/10 group-hover:bg-neutral-dark/5 transition-colors duration-500" />
                      </>
                    )}

                    <div className="relative z-10 w-full p-6 md:p-10 bg-gradient-to-t from-neutral-dark/95 via-neutral-dark/70 to-transparent flex flex-col pt-40">
                      <div className="flex flex-wrap items-center gap-4 mb-4">
                        {post.frontmatter.category && (
                          <Badge variant="accent" className="shadow-md">
                            {post.frontmatter.category}
                          </Badge>
                        )}
                        {(new Date(post.frontmatter.date) > new Date() ||
                          post.frontmatter.public === false) && (
                          <span className="px-2 py-0.5 border border-white/40 text-white/90 rounded uppercase tracking-widest text-[10px] md:text-xs font-bold bg-neutral-dark/40 shadow-sm">
                            Draft Preview
                          </span>
                        )}
                      </div>

                      <div className="flex items-center gap-3 text-xs md:text-sm font-bold text-white/80 mb-3 tracking-widest uppercase">
                        <time dateTime={post.frontmatter.date} suppressHydrationWarning>
                          {new Date(post.frontmatter.date).toLocaleDateString(
                            locale === 'en' ? 'en-US' : 'de-DE',
                            {
                              year: 'numeric',
                              month: 'long',
                              day: 'numeric',
                            },
                          )}
                        </time>
                      </div>

                      <h3 className="text-xl md:text-3xl font-bold text-white mb-4 group-hover:text-accent transition-colors drop-shadow-md leading-tight max-w-4xl">
                        {post.frontmatter.title}
                      </h3>

                      {post.frontmatter.excerpt && (
                        <p className="text-white/90 text-sm md:text-lg line-clamp-3 mb-6 max-w-4xl drop-shadow-sm leading-relaxed">
                          {post.frontmatter.excerpt}
                        </p>
                      )}

                      <div className="mt-auto flex items-center justify-between border-t border-white/20 pt-6">
                        <span className="text-accent text-sm md:text-base font-extrabold group-hover:text-white transition-colors">
                          {t('readMore')}
                        </span>
                        <div className="w-10 h-10 rounded-full bg-white/10 flex items-center justify-center text-accent group-hover:bg-accent group-hover:text-primary-dark transition-all duration-300 backdrop-blur-sm border border-white/20">
                          <svg
                            className="w-5 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${categoryParam ? `&category=${categoryParam}` : ''}`}
              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${categoryParam ? `&category=${categoryParam}` : ''}`}
              variant="outline"
              size="sm"
              className="md:h-11 md:px-6 md:text-base"
            >
              2
            </Button>
            <Button
              href={`/${locale}/blog?page=2${categoryParam ? `&category=${categoryParam}` : ''}`}
              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>
  );
}
