import React from 'react';
import Link from 'next/link';
import { ChevronRight } from 'lucide-react';
import { getAllCategoriesWithCount, getCategoryArticles } from '@/lib/utils/db';

interface ManualArticle {
  title?: string;
  image?: string;
  linkUrl?: string;
}

interface ManualCategory {
  categoryName?: string;
  articles?: ManualArticle[];
}

interface ArticleGridCategorySectionsProps {
  articlesPerCategory?: number;
  showViewMore?: string;
  theme?: string;
  dataMode?: string;
  manualCategories?: ManualCategory[];
}

export async function ArticleGridCategorySections({
  articlesPerCategory = 4,
  showViewMore = 'yes',
  theme = 'default',
  dataMode = 'auto',
  manualCategories = [],
}: ArticleGridCategorySectionsProps) {
  const useManual = dataMode === 'manual' && manualCategories.length > 0;

  const themeClasses: Record<string, { accent: string; badge: string; cardBg: string; border: string }> = {
    default: { accent: 'text-[#E60023]', badge: 'bg-[#E60023]', cardBg: 'bg-dark-gray', border: 'border-soft-gray-border/20' },
    warm: { accent: 'text-orange-600', badge: 'bg-orange-500', cardBg: 'bg-orange-50', border: 'border-orange-200' },
    professional: { accent: 'text-slate-200', badge: 'bg-slate-700', cardBg: 'bg-slate-800', border: 'border-slate-600' },
    ocean: { accent: 'text-blue-600', badge: 'bg-blue-500', cardBg: 'bg-blue-50', border: 'border-blue-200' },
    forest: { accent: 'text-emerald-600', badge: 'bg-emerald-500', cardBg: 'bg-emerald-50', border: 'border-emerald-200' },
  };
  const t = themeClasses[theme] || themeClasses.default;
  const bgClass = theme === 'professional' ? 'bg-slate-900 text-white' : 'bg-deep-black';

  // Build display data
  let categorySections: { category: string; count: number; articles: { slug: string; title: string; cardImage: string; publicationDate: any; isManual: boolean }[] }[];

  if (useManual) {
    categorySections = manualCategories.map((mc) => ({
      category: mc.categoryName || '未分類',
      count: mc.articles?.length || 0,
      articles: (mc.articles || []).map((a) => ({
        slug: a.linkUrl || '#',
        title: a.title || '',
        cardImage: a.image || '',
        publicationDate: null,
        isManual: true,
      })),
    }));
  } else {
    const categoriesWithCount = await getAllCategoriesWithCount();
    categorySections = await Promise.all(
      categoriesWithCount.map(async (cat) => {
        const articles = await getCategoryArticles(cat.name, articlesPerCategory);
        return {
          category: cat.name,
          count: cat.count,
          articles: articles.map((a) => ({
            slug: `/post/${a.slug}`,
            title: a.title,
            cardImage: a.cardImage || '',
            publicationDate: a.publicationDate,
            isManual: false,
          })),
        };
      })
    );
  }

  return (
    <section className={`w-full py-10 ${bgClass}`}>
      <div className="container max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 space-y-12">
        {categorySections.map((section) => (
          <div key={section.category}>
            <div className="flex items-center justify-between mb-6">
              <div className="flex items-center gap-3">
                <h2 className={`text-xl font-bold ${theme === 'professional' ? 'text-white' : 'text-white'}`}>
                  {section.category}
                </h2>
                <span className={`text-xs px-2 py-0.5 rounded-full ${t.badge} text-white font-medium`}>
                  {section.count}記事
                </span>
              </div>
              {showViewMore === 'yes' && !section.articles[0]?.isManual && (
                <Link
                  href={`/category/${encodeURIComponent(section.category)}`}
                  className={`flex items-center gap-1 text-sm font-medium ${t.accent} hover:underline`}
                >
                  すべて見る <ChevronRight className="w-4 h-4" />
                </Link>
              )}
            </div>
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
              {section.articles.map((article, idx) => {
                const Wrapper = article.isManual ? 'a' : Link;
                return (
                  <Wrapper
                    key={`${article.slug}-${idx}`}
                    href={article.slug}
                    className={`${t.cardBg} rounded-xl border ${t.border} overflow-hidden hover:shadow-md transition-all group`}
                  >
                    <div className="aspect-[16/9] bg-slate-200 relative">
                      {article.cardImage ? (
                        <img src={article.cardImage} alt={article.title} className="w-full h-full object-cover" />
                      ) : (
                        <div className="w-full h-full flex items-center justify-center text-slate-400 text-sm">No Image</div>
                      )}
                    </div>
                    <div className="p-3">
                      <h3 className={`font-semibold text-sm line-clamp-2 leading-snug ${
                        theme === 'professional' ? 'text-slate-100' : 'text-white'
                      }`}>
                        {article.title}
                      </h3>
                      {!article.isManual && article.publicationDate && (
                        <span className={`text-xs mt-2 block ${theme === 'professional' ? 'text-slate-400' : 'text-text-light-gray'}`}>
                          {new Date(article.publicationDate).toLocaleDateString('ja-JP').replace(/\//g, '.')}
                        </span>
                      )}
                    </div>
                  </Wrapper>
                );
              })}
            </div>
          </div>
        ))}
        {categorySections.length === 0 && (
          <p className="text-center text-text-light-gray py-8">カテゴリーが見つかりません</p>
        )}
      </div>
    </section>
  );
}
