import Link from 'next/link'
import { ArrowLeft } from 'lucide-react'
import type { ReactNode } from 'react'
import type { BlogPost as BlogPostType } from '@startsimpli/api/blog'
import { MarkdownRenderer } from './MarkdownRenderer'
import { JsonLd } from './JsonLd'
import { cn } from '../../utils/cn'

export interface BlogPostProps {
  post: BlogPostType
  /** Pre-resolved featured-image URL (pass the client's `getImageUrl`). */
  imageSrc?: string
  /** Index route, e.g. `/blog`. Used for breadcrumb + back link. */
  basePath?: string
  /** Label for the index in the breadcrumb / back link. Default "Blog". */
  indexLabel?: string
  /** Byline shown in the article meta. */
  byline?: string
  /** Syntax-highlight theme forwarded to the markdown renderer. */
  theme?: 'light' | 'dark'
  /** schema.org JSON-LD object(s) rendered into the page head. */
  structuredData?: object | object[]
  /** Left-rail outline, e.g. `<TableOfContents content={post.content} />`. Sticky on lg+. */
  toc?: ReactNode
  /** Optional sidebar (share widgets, CTAs). Rendered right of the content on lg+. */
  sidebar?: ReactNode
  className?: string
}

/**
 * Full article-detail composer: JSON-LD, breadcrumb, title, byline/date,
 * featured image, themed markdown body, optional sidebar, and back link.
 * Per-app code reduces to fetching the post and rendering `<BlogPost {...} />`.
 */
export function BlogPost({
  post,
  imageSrc,
  basePath = '/blog',
  indexLabel = 'Blog',
  byline,
  theme = 'light',
  structuredData,
  toc,
  sidebar,
  className,
}: BlogPostProps) {
  const featured = imageSrc ?? post.image
  const publishedLabel = post.publishedAt
    ? new Date(post.publishedAt).toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' })
    : null

  const mainColClass =
    toc && sidebar
      ? 'lg:col-span-6'
      : toc
        ? 'lg:col-span-9'
        : sidebar
          ? 'lg:col-span-8'
          : 'max-w-3xl mx-auto w-full'

  return (
    <article className={cn('py-12', className)}>
      {structuredData && <JsonLd data={structuredData} />}
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <nav className="mb-8 text-sm" aria-label="Breadcrumb">
          <ol className="flex items-center gap-2 text-muted-foreground">
            <li>
              <Link href="/" className="hover:text-primary transition-colors">
                Home
              </Link>
            </li>
            <li aria-hidden>/</li>
            <li>
              <Link href={basePath} className="hover:text-primary transition-colors">
                {indexLabel}
              </Link>
            </li>
            <li aria-hidden>/</li>
            <li className="text-foreground line-clamp-1">{post.title}</li>
          </ol>
        </nav>

        <div className={cn('grid grid-cols-1 gap-8 lg:gap-10', toc || sidebar ? 'lg:grid-cols-12' : '')}>
          {toc && (
            <aside className="hidden lg:block lg:col-span-3 order-first">
              <div className="sticky top-8">{toc}</div>
            </aside>
          )}
          <div className={mainColClass}>
            <h1 className="font-heading text-4xl md:text-5xl font-bold text-foreground mb-6">{post.title}</h1>

            <div className="flex items-center gap-4 mb-8 pb-8 border-b border-border text-sm text-muted-foreground">
              {byline && <span className="font-medium text-foreground">{byline}</span>}
              {publishedLabel && (
                <time dateTime={post.publishedAt}>{publishedLabel}</time>
              )}
              {post.readTime && (
                <>
                  <span aria-hidden>•</span>
                  <span>{post.readTime}</span>
                </>
              )}
            </div>

            {featured && (
              <div className="mb-10 rounded-xl overflow-hidden">
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img src={featured} alt={post.title} className="w-full h-auto" />
              </div>
            )}

            <MarkdownRenderer content={post.content} theme={theme} />

            <div className="mt-12 pt-8 border-t border-border">
              <Link
                href={basePath}
                className="inline-flex items-center gap-2 text-primary hover:opacity-80 font-medium transition-opacity"
              >
                <ArrowLeft className="w-5 h-5" />
                Back to {indexLabel}
              </Link>
            </div>
          </div>

          {sidebar && (
            <aside className={toc ? 'lg:col-span-3' : 'lg:col-span-4'}>
              <div className="sticky top-8 space-y-6">{sidebar}</div>
            </aside>
          )}
        </div>
      </div>
    </article>
  )
}
