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

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

interface HeroBlogCarouselEditorProps {
  sectionTitle?: string;
  articleCount?: number;
  bgImage?: string;
  showCategoryBadge?: string;
  showExcerpt?: string;
  theme?: string;
  dataMode?: string;
  manualItems?: ManualItem[];
}

export function HeroBlogCarouselEditor({
  sectionTitle = '最新記事',
  articleCount = 5,
  bgImage = '',
  showCategoryBadge = 'yes',
  showExcerpt = 'yes',
  theme = 'default',
  dataMode = 'auto',
  manualItems = [],
}: HeroBlogCarouselEditorProps) {
  const isManual = dataMode === 'manual';
  const showBadge = showCategoryBadge === 'yes';
  const showExcerptFlag = showExcerpt === 'yes';

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

  const themeColors: Record<string, { badge: string; gradient: string }> = {
    default: { badge: 'bg-crimson-red', gradient: 'from-brand-primary/40 to-brand-primary/10' },
    warm: { badge: 'bg-orange-500', gradient: 'from-orange-500/40 to-orange-300/10' },
    professional: { badge: 'bg-slate-600', gradient: 'from-slate-700/50 to-slate-500/10' },
    ocean: { badge: 'bg-blue-500', gradient: 'from-blue-500/40 to-indigo-300/10' },
    forest: { badge: 'bg-emerald-500', gradient: 'from-emerald-500/40 to-teal-300/10' },
  };
  const tc = themeColors[theme] || themeColors.default;

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

  if (loading && !isManual) {
    const sidebarCount = Math.max(0, articleCount - 1);
    return (
      <section className="w-full py-10">
        <div className="container max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          {sectionTitle && <h2 className="text-2xl font-bold text-white mb-6">{sectionTitle}</h2>}
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-4 animate-pulse">
            <div className={`lg:col-span-2 rounded-2xl overflow-hidden bg-gradient-to-br ${tc.gradient} min-h-[320px] flex flex-col justify-end p-6`}>
              <div className="h-7 bg-white/30 rounded w-3/4 mb-2" />
              {showExcerptFlag && <div className="h-4 bg-white/20 rounded w-1/2" />}
            </div>
            <div className="flex flex-col gap-3">
              {Array.from({ length: Math.min(sidebarCount, 4) }, (_, i) => (
                <div key={i} className={`rounded-xl bg-gradient-to-br ${tc.gradient} flex-1 min-h-[76px] flex flex-col justify-end p-3`}>
                  <div className="h-4 bg-white/25 rounded w-2/3" />
                </div>
              ))}
            </div>
          </div>
        </div>
      </section>
    );
  }

  const hasData = displayItems.length > 0;
  const hero = hasData ? displayItems[0] : null;
  const sidebar = hasData ? displayItems.slice(1) : [];

  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-2xl font-bold text-white">{sectionTitle}</h2>
            {isManual && <span className="text-[10px] px-2 py-0.5 bg-amber-100 text-amber-700 rounded-full font-medium">手動</span>}
          </div>
        )}
        {hasData ? (
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
            {/* Hero Main */}
            <a
              href={hero!.linkUrl}
              className="lg:col-span-2 rounded-2xl overflow-hidden relative min-h-[320px] flex flex-col justify-end p-6 shadow-md hover:opacity-95 block"
            >
              {hero!.image ? (
                <img src={hero!.image} alt={hero!.title} className="absolute inset-0 w-full h-full object-cover" />
              ) : (
                <div className="absolute inset-0 bg-slate-300" />
              )}
              <div className="absolute inset-0 bg-gradient-to-t from-black/70 via-black/30 to-transparent" />
              <div className="relative z-10">
                {showBadge && hero!.category && (
                  <span className={`text-[11px] font-bold px-3 py-1 rounded-full ${tc.badge} text-white w-fit mb-3 inline-block`}>{hero!.category}</span>
                )}
                <h3 className="text-white text-xl sm:text-2xl font-bold leading-tight line-clamp-2 mb-1">{hero!.title}</h3>
                {showExcerptFlag && hero!.excerpt && <p className="text-white/80 text-sm line-clamp-2">{hero!.excerpt}</p>}
              </div>
            </a>

            {/* Sidebar list */}
            <div className="flex flex-col gap-3">
              {sidebar.map((item, i) => (
                <a
                  key={i}
                  href={item.linkUrl}
                  className="rounded-xl overflow-hidden relative flex-1 min-h-[76px] flex flex-col justify-end p-3 shadow-sm hover:opacity-95 block"
                >
                  {item.image ? (
                    <img src={item.image} alt={item.title} className="absolute inset-0 w-full h-full object-cover" />
                  ) : (
                    <div className="absolute inset-0 bg-slate-300" />
                  )}
                  <div className="absolute inset-0 bg-gradient-to-t from-black/70 via-black/30 to-transparent" />
                  <div className="relative z-10">
                    {showBadge && item.category && (
                      <span className={`text-[10px] font-bold px-2 py-0.5 rounded-full ${tc.badge} text-white w-fit mb-1 inline-block`}>{item.category}</span>
                    )}
                    <h4 className="text-white text-sm font-semibold line-clamp-2 leading-snug">{item.title}</h4>
                  </div>
                </a>
              ))}
            </div>
          </div>
        ) : (
          <div className="p-8 rounded-xl border-2 border-dashed border-slate-300 text-center">
            <p className="text-sm text-text-light-gray">表示できる記事がありません</p>
          </div>
        )}
        <p className="text-center text-xs text-text-light-gray mt-4 italic">
          {isManual
            ? '※ 手動モード — 上記のアイテムがそのまま公開ページに表示されます'
            : '※ 自動モード — DBの最新記事を表示中'}
        </p>
      </div>
    </section>
  );
}
