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

interface BlogIndexProps {
  params: {
    locale: string;
  };
}

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

export default async function BlogIndex({ params: { locale } }: BlogIndexProps) {
  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>
        <section 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 && (
            <>
              <img
                src={featuredPost.frontmatter.featuredImage}
                alt={featuredPost.frontmatter.title}
                className="absolute inset-0 w-full h-full object-cover scale-105 animate-slow-zoom opacity-40 md:opacity-60"
              />
              <div className="absolute inset-0 image-overlay-gradient" />
            </>
          )}

          <Container className="relative z-10">
            <div className="max-w-4xl animate-slide-up">
              <Badge variant="saturated" className="mb-4 md:mb-6">
                {t('featuredPost')}
              </Badge>
              {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-2 md:line-clamp-2 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>
        </section>
      </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 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">
                        <img
                          src={post.frontmatter.featuredImage}
                          alt={post.frontmatter.title}
                          className="w-full h-full object-cover transition-transform duration-1000 group-hover:scale-110"
                        />
                        <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="text-[10px] md:text-sm font-bold text-accent-dark mb-2 md:mb-4 tracking-widest uppercase">
                        {new Date(post.frontmatter.date).toLocaleDateString(locale, {
                          year: 'numeric',
                          month: 'long',
                          day: 'numeric',
                        })}
                      </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-2 leading-tight">
                        {post.frontmatter.title}
                      </h3>
                      <p className="text-text-secondary text-sm md:text-lg line-clamp-2 md:line-clamp-3 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 Placeholder */}
          <div className="mt-12 md:mt-24 flex justify-center gap-2 md:gap-4">
            <Button variant="outline" size="sm" className="md:h-11 md:px-6 md:text-base" disabled>
              {t('prev')}
            </Button>
            <Button variant="primary" size="sm" className="md:h-11 md:px-6 md:text-base">
              1
            </Button>
            <Button variant="outline" size="sm" className="md:h-11 md:px-6 md:text-base">
              2
            </Button>
            <Button variant="outline" size="sm" className="md:h-11 md:px-6 md:text-base">
              {t('next')}
            </Button>
          </div>
        </Container>
      </Section>
    </div>
  );
}
