"use client";

import React, { useState } from 'react';
import { PhotoWithFallback, PaginationPageDefault } from '../elements';
import type { BlogPost } from '../../types/api/blog-post';

interface BlogGalleryProps {
  blogPosts?: BlogPost[] | null;
  postsPerPage?: number;
  className?: string;
}

export const BlogGallery = ({
  blogPosts: postsData,
  postsPerPage = 12,
  className = "",
}: BlogGalleryProps) => {
  const posts = Array.isArray(postsData) ? postsData : [];
  const [currentPage, setCurrentPage] = useState(1);

  // Get featured post (first post with featured: true or first post)
  const featuredPost = posts.find((post) => post.featured) || posts[0];
  const nonFeaturedPosts = posts.filter((post) => post.id !== featuredPost?.id);
  
  // Calculate pagination for non-featured posts
  const totalPages = Math.ceil(nonFeaturedPosts.length / postsPerPage);
  const startIndex = (currentPage - 1) * postsPerPage;
  const endIndex = startIndex + postsPerPage;
  const paginatedNonFeaturedPosts = nonFeaturedPosts.slice(startIndex, endIndex);

  return (
    <section className={className}>
      <div className="mx-auto max-w-container px-4 md:px-8">
        {posts.length > 0 ? (
          <>
            {/* Featured Post - Full Width */}
            {featuredPost && (
              <a
                href={`/blog/${featuredPost.slug}`}
                className="block mb-16 group"
              >
                <div className="w-full h-96 md:h-[500px] mb-8 overflow-hidden">
                  <PhotoWithFallback
                    item={featuredPost}
                    fallbackId={featuredPost.id}
                    className="w-full h-full object-cover transition-transform duration-300 group-hover:scale-105"
                  />
                </div>
                
                <div className="max-w-3xl">
                  <p className="text-xs font-body font-normal uppercase tracking-widest mb-4" style={{ color: 'var(--color-text-brand-secondary)' }}>
                    {featuredPost.published_at ? new Date(featuredPost.published_at).toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' }) : 'Recent'}
                  </p>
                  
                  <h2 className="font-display text-3xl md:text-4xl font-normal text-fg-primary mb-6 group-hover:underline">
                    {featuredPost.title}
                  </h2>
                  
                  {featuredPost.excerpt_markdown && (
                    <p className="font-display text-lg leading-relaxed text-tertiary">
                      {featuredPost.excerpt_markdown.replace(/[#*\[\]()]/g, '').trim()}
                    </p>
                  )}
                </div>
              </a>
            )}

            {/* Posts Grid */}
            {paginatedNonFeaturedPosts.length > 0 && (
              <div className="grid grid-cols-1 gap-12 md:grid-cols-2 lg:grid-cols-3 mb-16">
                {paginatedNonFeaturedPosts.map((post) => {
                  const excerpt = post.excerpt_markdown || post.content_markdown?.replace(/[#*\[\]()]/g, '').trim().substring(0, 150) || '';
                  
                  return (
                    <a key={post.id} href={`/blog/${post.slug}`} className="flex flex-col group">
                      <div className="w-full h-64 mb-6 overflow-hidden">
                        <PhotoWithFallback
                          item={post}
                          fallbackId={post.id}
                          className="w-full h-full object-cover transition-transform duration-300 group-hover:scale-105"
                        />
                      </div>
                      
                      <p className="text-xs font-body font-normal uppercase tracking-widest mb-2" style={{ color: 'var(--color-text-brand-secondary)' }}>
                        {post.published_at ? new Date(post.published_at).toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' }) : 'Recent'}
                      </p>
                      
                      <h3 className="font-display text-2xl font-normal text-fg-primary mb-4 group-hover:underline">
                        {post.title}
                      </h3>
                      
                      {excerpt && (
                        <p className="font-body text-base leading-relaxed text-tertiary mb-4 flex-grow line-clamp-3">
                          {excerpt}
                        </p>
                      )}
                    </a>
                  );
                })}
              </div>
            )}

            {/* Pagination */}
            {totalPages > 1 && (
              <div className="flex justify-center">
                <PaginationPageDefault 
                  rounded 
                  page={currentPage}
                  total={totalPages}
                  onPageChange={setCurrentPage}
                />
              </div>
            )}
          </>
        ) : (
          <div className="text-center py-12">
            <p className="font-body text-base text-tertiary">No posts available</p>
          </div>
        )}
      </div>
    </section>
  );
};

import { registerThemeVariant } from '../../lib/component-registry';
registerThemeVariant('blog-gallery', 'aman', BlogGallery);
