import React from 'react';
import Link from 'next/link';
import { Users } from 'lucide-react';
import { getLatestArticles } from '@/lib/utils/db';

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

interface BlogGridProps {
  title?: string;
  count?: number;
  columns?: 2 | 3 | 4;
  dataMode?: string;
  manualItems?: ManualItem[];
}

export async function BlogGrid({
  title = 'LATEST POSTS',
  count = 4,
  columns = 2,
  dataMode = 'auto',
  manualItems = [],
}: BlogGridProps) {
  const useManual = dataMode === 'manual' && manualItems.length > 0;
  const articles = useManual ? [] : await getLatestArticles(count);

  const displayItems = useManual
    ? manualItems.map((item) => ({
        slug: item.linkUrl || '#',
        title: item.title || '',
        cardImage: item.image || '',
        category: item.category || '',
        author: item.author || '',
        publicationDate: null,
        isManual: true,
      }))
    : articles.map((a) => ({
        slug: `/post/${a.slug}`,
        title: a.title,
        cardImage: a.cardImage || '',
        category: a.category || '',
        author: a.author || 'global-money-week2025.jp 編集部',
        publicationDate: a.publicationDate,
        isManual: false,
      }));

  return (
    <section className="w-full py-8">
      <div className="container max-w-5xl mx-auto px-4 sm:px-6 lg:px-8">
      {title && (
        <h2 className="text-2xl font-bold text-center mb-8 pb-4 border-b-2 border-hover-red inline-block relative left-1/2 -translate-x-1/2 text-white">
          {title}
        </h2>
      )}
      <div className={`grid grid-cols-1 md:grid-cols-${columns} gap-6`}>
        {displayItems.length > 0 ? (
          displayItems.map((item, i) => {
            const Wrapper = item.isManual ? 'a' : Link;
            const linkProps = item.isManual
              ? { href: item.slug }
              : { href: item.slug };

            return (
              <Wrapper
                {...linkProps}
                key={`${item.slug}-${i}`}
                className="bg-dark-gray rounded-xl shadow-sm border border-soft-gray-border/20 overflow-hidden hover:shadow-md transition-shadow cursor-pointer block hover-lift"
              >
                <div className="aspect-[16/9] bg-slate-200 relative">
                  {item.cardImage ? (
                    <img src={item.cardImage} alt={item.title} className="w-full h-full object-cover" />
                  ) : (
                    <div className="w-full h-full flex items-center justify-center text-slate-400">No Image</div>
                  )}
                  {item.category && (
                    <div className="absolute top-3 left-3 bg-[#E60023] text-white text-[11px] px-3 py-1 font-bold shadow-sm rounded-full tracking-wide">
                      {item.category}
                    </div>
                  )}
                </div>
                <div className="p-5 flex flex-col gap-3">
                  {!item.isManual && item.publicationDate && (
                    <div className="text-[12px] text-[#E60023] font-medium tracking-wide">
                      {new Date(item.publicationDate).toLocaleDateString('ja-JP').replace(/\//g, '.')}
                    </div>
                  )}
                  <h3 className="font-bold text-lg leading-snug line-clamp-2 text-white">{item.title}</h3>
                  <div className="flex items-center gap-2 mt-2">
                    <Users className="w-4 h-4 text-hover-red" />
                    <span className="text-[12px] font-medium text-text-light-gray truncate">{item.author || 'global-money-week2025.jp 編集部'}</span>
                  </div>
                </div>
              </Wrapper>
            );
          })
        ) : (
          <div className={`col-span-${columns} text-center py-8 text-[#B8B8C0] font-medium bg-[#202026] rounded-xl border border-dashed border-soft-gray-border/40`}>
            まだ記事がありません。
          </div>
        )}
      </div>
      </div>
    </section>
  );
}
