import { Metadata } from 'next';
import { notFound } from 'next/navigation';
import { Breadcrumb } from '@/components/ui/Breadcrumb';
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 { ArticleSchema } from '@/components/seo/ArticleSchema';
import { FAQSchema } from '@/components/seo/FAQSchema';
import { BreadcrumbSchema } from '@/components/seo/BreadcrumbSchema';
import { addHeadingIds, parseJsonField } from '@/lib/utils/content';
import { getArticleBySlug, getRelatedArticles } from '@/lib/utils/db';

interface PageProps {
  params: Promise<{
    slug: string;
  }>;
}

// Revalidate every 24 hours (86400 seconds)
export const revalidate = 86400;

// Use cached query for article fetching
async function getArticle(slug: string) {
  // Decode URL-encoded slug to handle Japanese characters
  const decodedSlug = decodeURIComponent(slug);
  console.log('[Article Page] Original slug:', slug);
  console.log('[Article Page] Decoded slug:', decodedSlug);
  return await getArticleBySlug(decodedSlug);
}

export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
  const { slug } = await params;
  const article = await getArticle(slug);

  if (!article) {
    return {
      title: '記事が見つかりません',
    };
  }

  const articleUrl = `https://ten-sura-game.com/post/${article.slug}`;
  
  // Parse keywords from string or use defaults
  const keywordsArray = article.keywords 
    ? article.keywords.split(',').map(k => k.trim())
    : ['転スラ', '転生したらスライムだった件', 'ゲーム攻略', '攻略情報', article.category || ''];

  return {
    title: article.metaTitle || article.title,
    description: article.metaDescription || article.excerpt || undefined,
    keywords: keywordsArray,
    authors: article.author ? [{ name: article.author }] : [{ name: '編集部' }],
    alternates: {
      canonical: articleUrl,
    },
    openGraph: {
      title: article.title,
      description: article.excerpt || undefined,
      url: articleUrl,
      siteName: 'ten-sura-game.com',
      locale: 'ja_JP',
      type: 'article',
      publishedTime: article.publicationDate?.toISOString(),
      modifiedTime: article.updatedAt?.toISOString(),
      authors: article.author ? [article.author] : ['編集部'],
      section: article.category || undefined,
      tags: keywordsArray,
      images: article.heroImage ? [
        {
          url: article.heroImage,
          width: 1200,
          height: 630,
          alt: article.title,
        },
      ] : [
        {
          url: '/og-image.jpg',
          width: 1200,
          height: 630,
          alt: article.title,
        },
      ],
    },
    twitter: {
      card: 'summary_large_image',
      title: article.title,
      description: article.excerpt || undefined,
      creator: '@tensura_game',
      images: article.heroImage ? [article.heroImage] : ['/og-image.jpg'],
    },
  };
}

export default async function ArticlePage({ params }: PageProps) {
  const { slug } = await params;
  const article = await getArticle(slug);

  if (!article) {
    notFound();
  }

  // Fetch related articles
  const relatedArticles = await getRelatedArticles(article.category, article.id);

  // Add IDs to headings in content for anchor linking
  const contentWithIds = addHeadingIds(article.content);

  // Breadcrumb items
  const breadcrumbItems = [
    { label: 'ホーム', href: '/' },
    ...(article.category ? [{ label: article.category, href: `/category/${article.category}` }] : []),
    { label: article.title },
  ];

  // Parse FAQ items for schema
  const faqItems = parseJsonField<Array<{ question: string; answer: string }>>(article.faqItems);
  
  // Parse AIO box
  const aioBox = parseJsonField<{ title?: string; content?: string }>(article.aioBox);
  
  // Parse videos
  const videos = parseJsonField<Array<{ videoId: string; title?: string; platform?: string }>>(article.videos);

  return (
    <>
      {/* Schema.org Article markup */}
      <ArticleSchema
        title={article.title}
        description={article.excerpt}
        image={article.heroImage}
        datePublished={article.publicationDate || article.createdAt}
        dateModified={article.updatedAt}
        author={article.author || '編集部'}
        url={`https://ten-sura-game.com/post/${article.slug}`}
      />

      {/* Schema.org FAQ markup */}
      {faqItems && faqItems.length > 0 && (
        <FAQSchema faqItems={faqItems} />
      )}

      {/* Schema.org Breadcrumb markup */}
      <BreadcrumbSchema items={breadcrumbItems} />

      <div className="min-h-screen bg-[#0F0F12]">
        <div className="container mx-auto px-4 py-8">
          {/* Breadcrumb */}
          <Breadcrumb items={breadcrumbItems} />

        {/* Article Header */}
        <ArticleHeader
          title={article.title}
          author={article.author || '編集部'}
          publicationDate={article.publicationDate || article.createdAt}
          readingTime={article.readingTime}
          category={article.category}
        />

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

        {/* Article Content - Single Column Layout */}
        <div className="max-w-4xl mx-auto">
          <article className="bg-[#202026] rounded-xl p-6 md:p-8 shadow-lg">
            <ArticleContent 
              content={contentWithIds}
              aioBox={aioBox}
              keyTakeaways={article.keyTakeaways as string | null}
              faqItems={faqItems}
              videos={videos}
            />

            {/* Author Box */}
            <AuthorBox
              author={article.author || '編集部'}
              authorBio={article.authorBio}
              authorProfileUrl={article.authorProfileUrl}
            />
          </article>
        </div>

        {/* Related Articles */}
        <RelatedArticles articles={relatedArticles} />
        </div>
      </div>
    </>
  );
}
