import React from 'react';
import Link from 'next/link';
import { getLatestArticles, getMostReadArticles } from '@/lib/utils/db';

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

interface ManualMostReadItem {
  title?: string;
  linkUrl?: string;
}

interface BlogShowcaseGridProps {
  viewAllText?: string;
  viewAllUrl?: string;
  mostReadTitle?: string;
  mostReadCount?: number;
  leftColumnCount?: number;
  bgColor?: string;
  theme?: string;
  dataMode?: string;
  manualArticleItems?: ManualArticleItem[];
  manualMostReadItems?: ManualMostReadItem[];
}

export async function BlogShowcaseGrid({
  viewAllText = 'すべてのブログを見る',
  viewAllUrl = '/blogs',
  mostReadTitle = 'よく読まれている',
  mostReadCount = 5,
  leftColumnCount = 2,
  bgColor = '#0F0F12',
  theme = 'default',
  dataMode = 'auto',
  manualArticleItems = [],
  manualMostReadItems = [],
}: BlogShowcaseGridProps) {
  const useManual = dataMode === 'manual';
  const useManualArticles = useManual && manualArticleItems.length > 0;
  const useManualMostRead = useManual && manualMostReadItems.length > 0;

  const [latestArticles, mostReadArticles] = await Promise.all([
    useManualArticles ? Promise.resolve([]) : getLatestArticles(leftColumnCount + 1),
    useManualMostRead ? Promise.resolve([]) : getMostReadArticles(mostReadCount),
  ]);

  // Left column items
  const leftItems = useManualArticles
    ? manualArticleItems.slice(0, leftColumnCount).map((item) => ({
        slug: item.linkUrl || '#', cardImage: item.image || '', isManual: true,
      }))
    : latestArticles.slice(0, leftColumnCount).map((a) => ({
        slug: `/post/${a.slug}`, cardImage: a.cardImage || '', isManual: false,
      }));

  // Center featured item
  const featuredItem = useManualArticles
    ? (manualArticleItems[leftColumnCount] || manualArticleItems[0])
      ? { slug: (manualArticleItems[leftColumnCount] || manualArticleItems[0])?.linkUrl || '#', cardImage: (manualArticleItems[leftColumnCount] || manualArticleItems[0])?.image || '', isManual: true }
      : null
    : latestArticles[leftColumnCount] || latestArticles[0]
      ? { slug: `/post/${(latestArticles[leftColumnCount] || latestArticles[0]).slug}`, cardImage: (latestArticles[leftColumnCount] || latestArticles[0]).cardImage || '', isManual: false }
      : null;

  // Most read items
  const mostReadItems = useManualMostRead
    ? manualMostReadItems.map((item) => ({
        title: item.title || '', slug: item.linkUrl || '#', isManual: true,
      }))
    : mostReadArticles.map((a) => ({
        title: a.title, slug: `/post/${a.slug}`, isManual: false,
      }));

  const themeClasses: Record<string, { text: string; accent: string; link: string }> = {
    default: { text: 'text-white', accent: 'text-[#E60023]', link: 'text-[#E60023]' },
    warm: { text: 'text-white', accent: 'text-orange-500', link: 'text-orange-500' },
    professional: { text: 'text-white', accent: 'text-gray-300', link: 'text-gray-300' },
    ocean: { text: 'text-white', accent: 'text-blue-400', link: 'text-blue-400' },
    forest: { text: 'text-white', accent: 'text-emerald-400', link: 'text-emerald-400' },
  };
  const t = themeClasses[theme] || themeClasses.default;

  return (
    <section className="w-full py-10" style={{ backgroundColor: bgColor || '#0F0F12' }}>
      <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-12 gap-6">
          {/* Left: Stacked thumbnail images */}
          <div className="md:col-span-3 space-y-4">
            {leftItems.map((item, idx) => {
              const Wrapper = item.isManual ? 'a' : Link;
              return (
                <Wrapper key={idx} href={item.slug} className="block group">
                  <div className="rounded-xl overflow-hidden shadow-sm hover:shadow-md transition-shadow">
                    {item.cardImage ? (
                      <img src={item.cardImage} alt="" className="w-full aspect-[4/3] object-cover group-hover:scale-105 transition-transform duration-300" />
                    ) : (
                      <div className="w-full aspect-[4/3] bg-[#202026] flex items-center justify-center text-sm text-[#B8B8C0]">📷</div>
                    )}
                  </div>
                </Wrapper>
              );
            })}
          </div>

          {/* Center: Featured article + CTA */}
          <div className="md:col-span-5 flex flex-col">
            {featuredItem && (
              featuredItem.isManual ? (
                <a href={featuredItem.slug} className="block group flex-1">
                  <div className="rounded-xl overflow-hidden shadow-md hover:shadow-xl transition-shadow h-full">
                    {featuredItem.cardImage ? (
                      <img src={featuredItem.cardImage} alt="" className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300 min-h-[300px]" />
                    ) : (
                      <div className="w-full h-full min-h-[300px] bg-[#202026] flex items-center justify-center text-sm text-[#B8B8C0]">📷</div>
                    )}
                  </div>
                </a>
              ) : (
                <Link href={featuredItem.slug} className="block group flex-1">
                  <div className="rounded-xl overflow-hidden shadow-md hover:shadow-xl transition-shadow h-full">
                    {featuredItem.cardImage ? (
                      <img src={featuredItem.cardImage} alt="" className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300 min-h-[300px]" />
                    ) : (
                      <div className="w-full h-full min-h-[300px] bg-[#202026] flex items-center justify-center text-sm text-[#B8B8C0]">📷</div>
                    )}
                  </div>
                </Link>
              )
            )}
            {viewAllText && (
              <Link
                href={viewAllUrl || '/blogs'}
                className={`mt-4 inline-flex items-center justify-center gap-2 px-6 py-3 rounded-full border-2 border-current text-sm font-semibold transition-colors mx-auto ${t.link} hover:opacity-80`}
              >
                {viewAllText}
              </Link>
            )}
          </div>

          {/* Right: Most Read numbered list */}
          <div className="md:col-span-4">
            <h3 className={`text-lg font-bold mb-5 ${t.text}`}>{mostReadTitle}</h3>
            <div className="space-y-4">
              {mostReadItems.map((item, i) => {
                const Wrapper = item.isManual ? 'a' : Link;
                return (
                  <Wrapper key={`mr-${i}`} href={item.slug} className="flex items-start gap-3 group">
                    <span className={`text-lg font-black min-w-[2rem] text-center ${t.accent} opacity-60`}>{i + 1}</span>
                    <h4 className={`text-sm font-medium leading-snug line-clamp-2 group-hover:underline ${t.text}`}>{item.title}</h4>
                  </Wrapper>
                );
              })}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}
