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

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

interface FeaturedArticleSpotlightEditorProps {
  sectionTitle?: string;
  articleCount?: number;
  theme?: string;
  dataMode?: string;
  manualItems?: ManualItem[];
}

export function FeaturedArticleSpotlightEditor({
  sectionTitle = '注目の記事',
  articleCount = 1,
  theme = 'default',
  dataMode = 'auto',
  manualItems = [],
}: FeaturedArticleSpotlightEditorProps) {
  const isManual = dataMode === 'manual';

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

  const themeClasses: Record<string, { text: string; sub: string; badge: string; accent: string; link: string; border: string }> = {
    default: { text: 'text-white', sub: 'text-text-light-gray', badge: 'bg-crimson-red text-white', accent: 'text-crimson-red', link: 'text-crimson-red', border: 'border-soft-gray-border/20' },
    warm: { text: 'text-slate-800', sub: 'text-slate-500', badge: 'bg-orange-500 text-white', accent: 'text-orange-600', link: 'text-orange-600', border: 'border-orange-200' },
    professional: { text: 'text-slate-800', sub: 'text-slate-500', badge: 'bg-slate-700 text-white', accent: 'text-slate-600', link: 'text-blue-600', border: 'border-slate-200' },
    ocean: { text: 'text-slate-800', sub: 'text-slate-500', badge: 'bg-blue-500 text-white', accent: 'text-blue-600', link: 'text-blue-600', border: 'border-blue-200' },
    forest: { text: 'text-slate-800', sub: 'text-slate-500', badge: 'bg-emerald-600 text-white', accent: 'text-emerald-600', link: 'text-emerald-600', border: 'border-emerald-200' },
  };
  const t = themeClasses[theme] || themeClasses.default;

  const displayItems = isManual
    ? manualItems.map((item) => ({
        slug: item.linkUrl || '#',
        title: item.title || '(タイトル未入力)',
        cardImage: item.image || '',
        metaDescription: item.excerpt || '',
        category: item.category || '',
        publishedAt: null,
      }))
    : (autoArticles || []).map((a) => ({
        slug: `/post/${a.slug}`,
        title: a.title,
        cardImage: a.cardImage || '',
        metaDescription: a.metaDescription || a.excerpt || '',
        category: a.category || '',
        publishedAt: a.publicationDate,
      }));

  return (
    <section className="w-full py-10">
      <div className="container max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        {sectionTitle && (
          <div className="flex items-center gap-2 mb-6">
            <h2 className={`text-xl sm:text-2xl font-bold ${t.text}`}>{sectionTitle}</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="space-y-8">
          {loading && !isManual ? (
            /* Loading skeleton */
            Array.from({ length: articleCount }, (_, i) => (
              <div key={i} className={`rounded-2xl overflow-hidden border ${t.border} shadow-sm animate-pulse`}>
                <div className="grid grid-cols-1 md:grid-cols-2">
                  <div className="relative aspect-[16/10] md:aspect-auto bg-slate-200 flex items-center justify-center min-h-[200px]">
                    <span className="text-slate-400 text-sm">📷 記事画像</span>
                  </div>
                  <div className="p-6 sm:p-8 flex flex-col justify-center">
                    <span className={`text-xs font-bold uppercase tracking-wider ${t.accent} mb-3`}>最新記事</span>
                    <div className="h-6 bg-slate-200 rounded w-3/4 mb-2" />
                    <div className="h-4 bg-slate-100 rounded w-full mb-1" />
                    <div className="h-4 bg-slate-100 rounded w-2/3 mb-4" />
                    <span className={`inline-flex items-center gap-1.5 text-sm font-semibold ${t.link}`}>
                      続きを読む <ArrowRight className="w-4 h-4" />
                    </span>
                  </div>
                </div>
              </div>
            ))
          ) : displayItems.length > 0 ? (
            /* Render items */
            displayItems.map((item, idx) => (
              <div key={`${item.slug}-${idx}`} className={`rounded-2xl overflow-hidden border ${t.border} shadow-sm`}>
                <div className="grid grid-cols-1 md:grid-cols-2">
                  <div className="relative aspect-[16/10] md:aspect-auto overflow-hidden min-h-[200px]">
                    {item.cardImage ? (
                      <img src={item.cardImage} alt={item.title} className="w-full h-full object-cover" />
                    ) : (
                      <div className="w-full h-full bg-slate-200 flex items-center justify-center">
                        <span className="text-slate-400 text-sm">📷 画像を追加</span>
                      </div>
                    )}
                    {item.category && (
                      <span className={`absolute top-4 left-4 px-3 py-1.5 text-xs font-bold rounded-md ${t.badge}`}>{item.category}</span>
                    )}
                  </div>
                  <div className="p-6 sm:p-8 flex flex-col justify-center">
                    <div className="flex items-center gap-3 mb-3">
                      <span className={`text-xs font-bold uppercase tracking-wider ${t.accent}`}>最新記事</span>
                      {item.publishedAt && (
                        <span className="flex items-center gap-1 text-xs text-text-light-gray">
                          <Clock className="w-3.5 h-3.5" />
                          {new Date(item.publishedAt).toLocaleDateString('ja-JP', { year: 'numeric', month: '2-digit', day: '2-digit' })}
                        </span>
                      )}
                    </div>
                    <h3 className={`text-lg sm:text-xl font-bold leading-tight mb-3 ${t.text}`}>
                      {item.title}
                    </h3>
                    {item.metaDescription && <p className={`text-sm leading-relaxed line-clamp-3 mb-4 ${t.sub}`}>{item.metaDescription}</p>}
                    <span className={`inline-flex items-center gap-1.5 text-sm font-semibold ${t.link}`}>
                      続きを読む <ArrowRight className="w-4 h-4" />
                    </span>
                  </div>
                </div>
              </div>
            ))
          ) : isManual ? (
            <div className="p-6 rounded-xl border-2 border-dashed border-slate-300 text-center">
              <p className="text-sm text-text-light-gray">「Manual Items」にアイテムを追加してください</p>
            </div>
          ) : (
            <div className="p-6 rounded-xl border-2 border-dashed border-slate-300 text-center">
              <p className="text-sm text-text-light-gray mb-1">注目記事が見つかりません</p>
              <p className="text-xs text-slate-400">記事の「featured」フラグを有効にしてください</p>
            </div>
          )}
        </div>
        <p className="text-center text-xs text-text-light-gray mt-4 italic">
          {isManual
            ? '※ 手動モード — 上記のアイテムがそのまま公開ページに表示されます'
            : '※ 自動モード — DBの注目記事を表示中'}
        </p>
      </div>
    </section>
  );
}
