import { Metadata } from 'next';
import { notFound } from 'next/navigation';
import { Breadcrumb } from '@/components/ui/Breadcrumb';
import { AuthorProfile } from '@/components/author/AuthorProfile';
import { ArticleCard } from '@/components/article/ArticleCard';
import { Pagination } from '@/components/ui/Pagination';
import { 
  getArticlesByAuthor, 
  getAuthorArticleCount, 
  getAuthorInfo,
  getPaginationParams,
  calculateTotalPages 
} from '@/lib/utils/db';

interface PageProps {
  params: Promise<{
    authorSlug: string;
  }>;
  searchParams: Promise<{
    page?: string;
  }>;
}

export const revalidate = 60;

async function getAuthorData(authorSlug: string) {
  const decodedAuthor = decodeURIComponent(authorSlug);
  return {
    authorName: decodedAuthor,
    authorInfo: await getAuthorInfo(decodedAuthor),
  };
}

export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
  const { authorSlug } = await params;
  const { authorName, authorInfo } = await getAuthorData(authorSlug);

  if (!authorInfo) {
    return {
      title: '著者が見つかりません',
    };
  }

  const authorUrl = `https://alicey.jp/author/${authorSlug}`;
  const keywords = ['ALICEY', 'アリシィー', authorName, '著者', 'ライター', '記事一覧', '女性', 'ライフスタイル'];

  return {
    title: `${authorName} の記事一覧 | ALICEY（アリシィー）`,
    description: authorInfo.authorBio || `${authorName} が執筆した記事の一覧です。女性のためのライフスタイル情報メディアALICEY（アリシィー）`,
    keywords,
    alternates: {
      canonical: authorUrl,
    },
    openGraph: {
      title: `${authorName} の記事一覧 | ALICEY（アリシィー）`,
      description: authorInfo.authorBio || `${authorName} が執筆した記事の一覧です。`,
      url: authorUrl,
      siteName: 'ALICEY',
      locale: 'ja_JP',
      type: 'profile',
      images: [
        {
          url: '/og-image.jpg',
          width: 1200,
          height: 630,
          alt: `${authorName} - ALICEY`,
        },
      ],
    },
    twitter: {
      card: 'summary_large_image',
      title: `${authorName} の記事一覧 | ALICEY（アリシィー）`,
      description: authorInfo.authorBio || `${authorName} が執筆した記事の一覧です。`,
      creator: '@alicey_jp',
      images: ['/og-image.jpg'],
    },
  };
}

export default async function AuthorPage({ params, searchParams }: PageProps) {
  const { authorSlug } = await params;
  const resolvedSearchParams = await searchParams;
  const { authorName, authorInfo } = await getAuthorData(authorSlug);

  if (!authorInfo) {
    notFound();
  }

  // Pagination
  const currentPage = parseInt(resolvedSearchParams.page || '1', 10);
  const itemsPerPage = 12;
  const { offset, limit } = getPaginationParams(currentPage, itemsPerPage);

  // Fetch articles and count
  const [articles, totalCount] = await Promise.all([
    getArticlesByAuthor(authorName, limit, offset),
    getAuthorArticleCount(authorName),
  ]);

  const totalPages = calculateTotalPages(totalCount, itemsPerPage);

  // Breadcrumb items
  const breadcrumbItems = [
    { label: 'ホーム', href: '/' },
    { label: 'ブログ', href: '/blogs' },
    { label: authorName },
  ];

  return (
    <div className="container mx-auto px-4 py-8" suppressHydrationWarning>
      {/* Breadcrumb */}
      <Breadcrumb items={breadcrumbItems} />

      {/* Author Profile */}
      <AuthorProfile
        author={authorName}
        authorBio={authorInfo.authorBio}
        articleCount={totalCount}
      />

      {/* Articles Section */}
      {articles.length > 0 ? (
        <>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-8">
            {articles.map((article) => (
              <ArticleCard
                key={article.slug}
                article={{
                  slug: article.slug,
                  title: article.title,
                  excerpt: article.excerpt,
                  cardImage: article.cardImage,
                  publicationDate: article.publicationDate,
                  category: article.category,
                  readingTime: article.readingTime,
                }}
              />
            ))}
          </div>

          {/* Pagination */}
          {totalPages > 1 && (
            <Pagination
              currentPage={currentPage}
              totalPages={totalPages}
              baseUrl={`/author/${authorSlug}`}
            />
          )}
        </>
      ) : (
        <div className="text-center py-12">
          <p className="text-gray-400 text-lg">まだ記事がありません</p>
        </div>
      )}
    </div>
  );
}
