import Link from 'next/link'
import type { ReactNode } from 'react'
import type { BlogPost, BlogPagination } from '@startsimpli/api/blog'
import { ArticleCard } from './ArticleCard'
import { cn } from '../../utils/cn'

export interface BlogIndexProps {
  posts: BlogPost[]
  pagination: BlogPagination
  /** Current page (1-based). */
  page: number
  /** Route the index lives at, e.g. `/blog`. Used for card links + pagination. */
  basePath?: string
  /** Resolve a post's image URL (pass the client's `getImageUrl`). */
  getImageUrl?: (url?: string | null) => string
  /** Byline shown on each card (typically the site name). */
  byline?: string
  /** Hero copy. */
  eyebrow?: string
  title: string
  subtitle?: string
  /** Rendered in place of the grid when there are no posts. */
  emptyState?: ReactNode
  className?: string
}

/**
 * Full blog index composer: hero + responsive card grid + windowed pagination.
 * Apps supply data + copy; everything is themed with shared tokens. Per-app
 * code reduces to fetching posts and rendering `<BlogIndex {...} />`.
 */
export function BlogIndex({
  posts,
  pagination,
  page,
  basePath = '/blog',
  getImageUrl,
  byline,
  eyebrow,
  title,
  subtitle,
  emptyState,
  className,
}: BlogIndexProps) {
  const pageHref = (p: number) => (p <= 1 ? basePath : `${basePath}?page=${p}`)

  return (
    <div className={cn('flex flex-col', className)}>
      <section className="bg-gradient-to-b from-muted to-background py-12 md:py-16">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 text-center">
          {eyebrow && (
            <span className="inline-block mb-4 rounded-full bg-primary/10 text-primary border border-primary/20 px-3 py-1 text-sm font-medium">
              {eyebrow}
            </span>
          )}
          <h1 className="font-heading text-4xl sm:text-5xl font-bold text-foreground mb-4">{title}</h1>
          {subtitle && <p className="text-xl text-muted-foreground max-w-2xl mx-auto">{subtitle}</p>}
        </div>
      </section>

      <section className="py-12 bg-background">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          {posts.length === 0 ? (
            emptyState ?? (
              <div className="text-center py-12 text-muted-foreground">No articles yet — check back soon.</div>
            )
          ) : (
            <>
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
                {posts.map((post) => (
                  <ArticleCard
                    key={post.id}
                    post={post}
                    href={`${basePath}/${post.slug}`}
                    imageSrc={getImageUrl ? getImageUrl(post.image) : post.image}
                    byline={byline}
                  />
                ))}
              </div>

              {pagination.pageCount > 1 && (
                <div className="mt-12 flex justify-center items-center gap-2">
                  {page > 1 && (
                    <Link
                      href={pageHref(page - 1)}
                      className="px-4 py-2 border border-border rounded-lg text-muted-foreground hover:bg-muted transition-colors"
                    >
                      Previous
                    </Link>
                  )}
                  <div className="flex items-center gap-2">
                    {Array.from({ length: pagination.pageCount }, (_, i) => i + 1)
                      .filter((p) => p === 1 || p === pagination.pageCount || Math.abs(p - page) <= 1)
                      .map((p, idx, arr) => {
                        const prev = arr[idx - 1]
                        const showEllipsis = prev && p - prev > 1
                        return (
                          <span key={p} className="flex items-center gap-2">
                            {showEllipsis && <span className="px-2 text-muted-foreground">…</span>}
                            <Link
                              href={pageHref(p)}
                              className={cn(
                                'px-4 py-2 rounded-lg transition-colors',
                                p === page
                                  ? 'bg-primary text-primary-foreground'
                                  : 'border border-border text-muted-foreground hover:bg-muted',
                              )}
                            >
                              {p}
                            </Link>
                          </span>
                        )
                      })}
                  </div>
                  {page < pagination.pageCount && (
                    <Link
                      href={pageHref(page + 1)}
                      className="px-4 py-2 border border-border rounded-lg text-muted-foreground hover:bg-muted transition-colors"
                    >
                      Next
                    </Link>
                  )}
                </div>
              )}

              <div className="mt-8 text-center text-sm text-muted-foreground">
                Showing {posts.length} of {pagination.total} articles
              </div>
            </>
          )}
        </div>
      </section>
    </div>
  )
}
