import React from 'react';
import type { Metadata } from 'next';
import Link from 'next/link';
import Image from 'next/image';
import SeoJsonLd from '@/components/SeoJsonLd';
import { websiteSchema, breadcrumbSchema } from '@/lib/schema';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/Card';
import { Badge } from '@/components/ui/Badge';
import Breadcrumbs, { BreadcrumbItem } from '@/components/Breadcrumbs';
import { blogPosts } from '@/lib/blog-data';

// Enable Incremental Static Regeneration (ISR)
// Revalidate every hour
export const revalidate = 3600;

function truncateAtWord(text: string, maxLength: number): string {
  if (text.length <= maxLength) return text;
  const truncated = text.slice(0, maxLength);
  const lastSpace = truncated.lastIndexOf(' ');
  return lastSpace > 0 ? truncated.slice(0, lastSpace) : truncated;
}

export async function generateMetadata(): Promise<Metadata> {
  const title = truncateAtWord('QR Insights: Latest QR Strategies', 60);
  const description = truncateAtWord(
    'Expert guides on QR code strategies, marketing campaigns, tracking analytics, and best practices for small businesses and enterprises.',
    160
  );

  return {
    title,
    description,
    alternates: {
      canonical: 'https://www.qrmaster.net/blog',
      languages: {
        'x-default': 'https://www.qrmaster.net/blog',
        en: 'https://www.qrmaster.net/blog',
      },
    },
    openGraph: {
      title,
      description,
      url: 'https://www.qrmaster.net/blog',
      type: 'website',
      images: ['/og-image.png'],
    },
    twitter: {
      title,
      description,
    },
  };
}

export default function BlogPage() {
  const breadcrumbItems: BreadcrumbItem[] = [
    { name: 'Home', url: '/' },
    { name: 'Blog', url: '/blog' },
  ];

  // Filter posts to only show those published in the past or today
  // sort by date descending (newest first)
  const currentDate = new Date();

  const publishedPosts = blogPosts
    .filter(post => {
      const publishDate = post.datePublished ? new Date(post.datePublished) : new Date(post.date);
      return publishDate <= currentDate;
    })
    .sort((a, b) => {
      const dateA = a.datePublished ? new Date(a.datePublished) : new Date(a.date);
      const dateB = b.datePublished ? new Date(b.datePublished) : new Date(b.date);
      return dateB.getTime() - dateA.getTime();
    });

  return (
    <>
      <SeoJsonLd data={[websiteSchema(), breadcrumbSchema(breadcrumbItems)]} />
      <div className="py-20 bg-gradient-to-b from-gray-50 to-white">
        <div className="container mx-auto px-4">
          <Breadcrumbs items={breadcrumbItems} />
          <div className="text-center mb-16">
            <h1 className="text-4xl lg:text-5xl font-bold text-gray-900 mb-6">
              QR Code Insights
            </h1>
            <p className="text-xl text-gray-600 max-w-2xl mx-auto">
              Expert guides on dynamic QR codes, campaign tracking, UTM analytics, and smart marketing use cases.
              Discover how-to tutorials and best practices for QR code analytics.
            </p>
          </div>

          <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-8 max-w-6xl mx-auto">
            {publishedPosts.map((post) => (
              <Link key={post.slug} href={`/blog/${post.slug}`}>
                <Card hover className="h-full overflow-hidden shadow-md hover:shadow-xl transition-all duration-300">
                  <div className="relative h-56 overflow-hidden">
                    <Image
                      src={post.image}
                      alt={post.imageAlt || `${post.title} - QR code guide`}
                      width={800}
                      height={600}
                      unoptimized={post.image.endsWith('.svg')}
                      className="w-full h-full object-cover transition-transform duration-500 hover:scale-110"
                    />
                  </div>
                  <CardHeader className="pb-3">
                    <div className="flex items-center justify-between mb-3">
                      <Badge variant="info">{post.category}</Badge>
                      <span className="text-sm text-gray-500 font-medium">{post.readTime} read</span>
                    </div>
                    <CardTitle className="text-xl leading-tight mb-3">{post.title}</CardTitle>
                  </CardHeader>
                  <CardContent className="pt-0">
                    <p className="text-gray-600 mb-4 leading-relaxed">{post.excerpt}</p>
                    <div className="flex items-center justify-between pt-4 border-t border-gray-100">
                      <p className="text-sm text-gray-500">{post.date}</p>
                      <span className="text-primary-600 text-sm font-medium">Read more →</span>
                    </div>
                  </CardContent>
                </Card>
              </Link>
            ))}
          </div>
        </div>
      </div>
    </>
  );
}
