import React from 'react';
import Link from 'next/link';
import { TrendingUp, Crown } from 'lucide-react';
import { getTrendingArticles, getMostReadArticles } from '@/lib/utils/db';

interface ManualItem {
  title: string;
  image?: string;
  linkUrl?: string;
  category?: string;
}

interface ArticleGridTrendingRankingProps {
  trendingTitle?: string;
  rankingTitle?: string;
  trendingCount?: number;
  rankingCount?: number;
  showTrending?: string;
  showRanking?: string;
  trendingMode?: string;
  rankingMode?: string;
  manualTrendingItems?: ManualItem[];
  manualRankingItems?: ManualItem[];
  theme?: string;
}

export async function ArticleGridTrendingRanking({
  trendingTitle = 'いま話題',
  rankingTitle = '人気記事ランキング',
  trendingCount = 5,
  rankingCount = 5,
  showTrending = 'yes',
  showRanking = 'yes',
  trendingMode = 'auto',
  rankingMode = 'auto',
  manualTrendingItems = [],
  manualRankingItems = [],
  theme = 'default',
}: ArticleGridTrendingRankingProps) {
  // Use manual items if mode=manual and items exist, otherwise fetch from DB
  const useManualTrending = trendingMode === 'manual' && manualTrendingItems.length > 0;
  const useManualRanking = rankingMode === 'manual' && manualRankingItems.length > 0;

  const [trendingArticles, rankingArticles] = await Promise.all([
    showTrending === 'yes' && !useManualTrending
      ? getTrendingArticles(trendingCount)
      : Promise.resolve([]),
    showRanking === 'yes' && !useManualRanking
      ? getMostReadArticles(rankingCount)
      : Promise.resolve([]),
  ]);

  // Build display arrays
  const trendingDisplay = useManualTrending
    ? manualTrendingItems.map((item) => ({
        title: item.title,
        slug: item.linkUrl || '#',
        readingTime: null,
        isManual: true,
      }))
    : trendingArticles.map((a) => ({
        title: a.title,
        slug: `/post/${a.slug}`,
        readingTime: a.readingTime,
        isManual: false,
      }));

  const rankingDisplay = useManualRanking
    ? manualRankingItems.map((item) => ({
        title: item.title,
        slug: item.linkUrl || '#',
        cardImage: item.image || '',
        isManual: true,
      }))
    : rankingArticles.map((a) => ({
        title: a.title,
        slug: `/post/${a.slug}`,
        cardImage: a.cardImage || '',
        isManual: false,
      }));

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

  return (
    <section className={`w-full py-10 ${bgClass}`}>
      <div className="container max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
          {/* Trending Section */}
          {showTrending === 'yes' && (
            <div>
              <div className="flex items-center gap-2 mb-6">
                <TrendingUp className={`w-5 h-5 ${t.accent}`} />
                <h2 className={`text-xl font-bold ${theme === 'professional' ? 'text-white' : 'text-white'}`}>
                  {trendingTitle}
                </h2>
              </div>
              <div className="space-y-4">
                {trendingDisplay.map((item, i) => {
                  const Wrapper = item.isManual ? 'a' : Link;
                  return (
                  <Wrapper
                    key={`t-${i}`}
                    href={item.slug}
                    className={`flex items-start gap-4 p-3 rounded-xl border ${t.border} hover:shadow-md transition-all group ${
                      theme === 'professional' ? 'bg-slate-800/50 hover:bg-slate-800' : 'bg-dark-gray hover:bg-[#202026]'
                    }`}
                  >
                    <span className={`text-2xl font-black ${t.accent} opacity-40 min-w-[2rem] text-center`}>
                      {String(i + 1).padStart(2, '0')}
                    </span>
                    <div className="flex-1 min-w-0">
                      <h3 className={`font-semibold text-sm leading-snug line-clamp-2 transition-colors ${
                        theme === 'professional' ? 'text-slate-100' : 'text-white'
                      }`}>
                        {item.title}
                      </h3>
                      {item.readingTime && (
                        <span className={`text-xs mt-1 block ${theme === 'professional' ? 'text-slate-400' : 'text-text-light-gray'}`}>
                          {item.readingTime}分で読める
                        </span>
                      )}
                    </div>
                  </Wrapper>
                  );
                })}
                {trendingDisplay.length === 0 && (
                  <p className="text-sm text-text-light-gray text-center py-4">記事がありません</p>
                )}
              </div>
            </div>
          )}

          {/* Ranking Section */}
          {showRanking === 'yes' && (
            <div>
              <div className="flex items-center gap-2 mb-6">
                <Crown className={`w-5 h-5 ${t.accent}`} />
                <h2 className={`text-xl font-bold ${theme === 'professional' ? 'text-white' : 'text-white'}`}>
                  {rankingTitle}
                </h2>
              </div>
              <div className="space-y-3">
                {rankingDisplay.map((item, i) => {
                  const Wrapper = item.isManual ? 'a' : Link;
                  return (
                  <Wrapper
                    key={`r-${i}`}
                    href={item.slug}
                    className={`flex items-center gap-3 p-3 rounded-xl border ${t.border} hover:shadow-md transition-all group ${
                      theme === 'professional' ? 'bg-slate-800/50 hover:bg-slate-800' : 'bg-dark-gray hover:bg-[#202026]'
                    }`}
                  >
                    <span className={`w-8 h-8 rounded-full ${i < 3 ? t.badge + ' text-white' : 'bg-slate-200 text-[#B8B8C0]'} flex items-center justify-center text-sm font-bold shrink-0`}>
                      {i + 1}
                    </span>
                    {item.cardImage && (
                      <img
                        src={item.cardImage}
                        alt={item.title}
                        className="w-16 h-12 object-cover rounded-lg shrink-0"
                      />
                    )}
                    <h3 className={`font-medium text-sm line-clamp-2 flex-1 ${
                      theme === 'professional' ? 'text-slate-100' : 'text-white'
                    }`}>
                      {item.title}
                    </h3>
                  </Wrapper>
                  );
                })}
                {rankingDisplay.length === 0 && (
                  <p className="text-sm text-text-light-gray text-center py-4">記事がありません</p>
                )}
              </div>
            </div>
          )}
        </div>
      </div>
    </section>
  );
}
