import React from 'react';
import { Users } from 'lucide-react';
import { useEditorData } from '@/hooks/useEditorData';
import type { Article } from '@/lib/utils/db';

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

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

export function BlogGridEditor({
  title = 'LATEST POSTS',
  count = 4,
  columns = 2,
  dataMode = 'auto',
  manualItems = [],
}: BlogGridEditorProps) {
  const isManual = dataMode === 'manual';

  const { data: autoArticles, loading } = useEditorData<Article[]>({
    type: 'latest',
    count: count,
    skip: isManual,
  });

  const displayItems = isManual
    ? manualItems.map((item) => ({
        slug: item.linkUrl || '#',
        title: item.title || '(タイトル未入力)',
        cardImage: item.image || '',
        category: item.category || '',
        author: item.author || 'global-money-week2025.jp 編集部',
        publicationDate: null,
      }))
    : (autoArticles || []).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,
      }));

  return (
    <section className="w-full py-8">
      <div className="container max-w-5xl mx-auto px-4 sm:px-6 lg:px-8">
        {title && (
          <div className="flex items-center justify-center gap-2 mb-8">
            <h2 className="text-2xl font-bold text-center pb-4 border-b-2 border-hover-red text-white">
              {title}
            </h2>
            {isManual && (
              <span className="text-[10px] px-2 py-0.5 bg-amber-100 text-amber-700 rounded-full font-medium">手動</span>
            )}
          </div>
        )}
        <div className={`grid grid-cols-1 md:grid-cols-${columns} gap-6`}>
          {loading && !isManual ? (
            /* Loading skeleton */
            Array.from({ length: count }, (_, i) => (
              <div key={i} className="bg-dark-gray rounded-xl shadow-sm border border-soft-gray-border/20 overflow-hidden animate-pulse">
                <div className="aspect-[16/9] bg-slate-200" />
                <div className="p-5 flex flex-col gap-3">
                  <div className="h-3 bg-slate-200 rounded w-1/4" />
                  <div className="h-5 bg-slate-200 rounded w-3/4" />
                  <div className="flex items-center gap-2 mt-2">
                    <Users className="w-4 h-4 text-hover-red" />
                    <div className="h-3 bg-slate-100 rounded w-1/3" />
                  </div>
                </div>
              </div>
            ))
          ) : displayItems.length > 0 ? (
            displayItems.map((item, i) => (
              <a
                href={item.slug}
                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"
              >
                <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-crimson-red text-white text-[11px] px-3 py-1 font-bold shadow-sm rounded-full">
                      {item.category}
                    </div>
                  )}
                </div>
                <div className="p-5 flex flex-col gap-3">
                  {item.publicationDate && (
                    <div className="text-[12px] text-crimson-red 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}
                    </span>
                  </div>
                </div>
              </a>
            ))
          ) : isManual ? (
            <div className={`col-span-${columns} p-6 rounded-xl border-2 border-dashed border-soft-gray-border/40 text-center`}>
              <p className="text-sm text-text-light-gray">「Manual Items」にアイテムを追加してください</p>
            </div>
          ) : (
            <div className={`col-span-${columns} p-6 rounded-xl border-2 border-dashed border-soft-gray-border/40 text-center`}>
              <p className="text-sm text-text-light-gray">記事がありません</p>
            </div>
          )}
        </div>
        <p className="text-center text-xs text-text-light-gray mt-4 italic">
          {isManual
            ? '※ 手動モード — 上記のアイテムがそのまま公開ページに表示されます'
            : '※ 自動モード — DBの最新記事を表示中'}
        </p>
      </div>
    </section>
  );
}
