import React from 'react';
import { getArticleBySlug, getRelatedArticles } from '@/lib/utils/db';
import { ArticleHeader } from '@/components/article/ArticleHeader';
import { HeroImage } from '@/components/article/HeroImage';
import { ArticleContent } from '@/components/article/ArticleContent';
import { AuthorBox } from '@/components/article/AuthorBox';
import { RelatedArticles } from '@/components/article/RelatedArticles';
import { addHeadingIds } from '@/lib/utils/content';

interface BlogPostProps {
  slug?: string;
  anchorId?: string;
}

export async function BlogPost({ slug, anchorId }: BlogPostProps) {
  if (!slug) {
    return (
      <section className="w-full py-8 text-center text-gray-500" id={anchorId || undefined}>
        Please select a blog post.
      </section>
    );
  }

  const decodedSlug = decodeURIComponent(slug);
  const article = await getArticleBySlug(decodedSlug);

  if (!article) {
    return (
      <section className="w-full py-8 text-center text-red-500 font-medium" id={anchorId || undefined}>
        Blog post not found: {decodedSlug}
      </section>
    );
  }

  const relatedArticles = await getRelatedArticles(article.category, article.id);
  const contentWithIds = addHeadingIds(article.content);

  return (
    <section className="w-full py-8 bg-white" id={anchorId || undefined}>
      <div className="container mx-auto px-4 pb-8">
        <ArticleHeader
          title={article.title}
          author={article.author || '編集部'}
          publicationDate={article.publicationDate || article.createdAt}
          readingTime={article.readingTime}
          category={article.category}
        />

        {article.heroImage && (
          <HeroImage src={article.heroImage} alt={article.title} />
        )}

        <div className="max-w-4xl mx-auto">
          <article>
            <ArticleContent content={contentWithIds} />
            <AuthorBox
              author={article.author || '編集部'}
              authorBio={article.authorBio}
              authorProfileUrl={article.authorProfileUrl}
            />
          </article>
        </div>

        {relatedArticles && relatedArticles.length > 0 && (
          <RelatedArticles articles={relatedArticles} />
        )}
      </div>
    </section>
  );
}
