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

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

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

export function BlogShowcaseGridEditor({
  viewAllText = 'すべてのブログを見る',
  viewAllUrl = '/blog',
  mostReadTitle = 'よく読まれている',
  mostReadCount = 5,
  leftColumnCount = 2,
  bgColor = '#fefce8',
  theme = 'default',
  dataMode = 'auto',
  manualArticleItems = [],
  manualMostReadItems = [],
}: BlogShowcaseGridEditorProps) {
  const isManual = dataMode === 'manual';
  const totalNeeded = leftColumnCount + 1;

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

  const themeClasses: Record<string, { text: string; accent: string; link: string }> = {
    default: { text: 'text-[#222222]', accent: 'text-[#E53935]', link: 'text-[#E53935]' },
    warm: { text: 'text-slate-800', accent: 'text-orange-600', link: 'text-orange-600' },
    professional: { text: 'text-slate-800', accent: 'text-slate-700', link: 'text-slate-700' },
    ocean: { text: 'text-slate-800', accent: 'text-blue-600', link: 'text-blue-600' },
    forest: { text: 'text-slate-800', accent: 'text-emerald-600', link: 'text-emerald-600' },
  };
  const t = themeClasses[theme] || themeClasses.default;

  const sideArticles = isManual
    ? manualArticleItems.slice(0, leftColumnCount)
    : (autoArticles || []).slice(0, leftColumnCount).map((a) => ({ image: a.cardImage, title: a.title, linkUrl: a.slug }));

  const featuredArticle = isManual
    ? manualArticleItems[leftColumnCount]
    : (autoArticles || [])[leftColumnCount]
      ? {
          image: (autoArticles || [])[leftColumnCount].cardImage,
          title: (autoArticles || [])[leftColumnCount].title,
          linkUrl: (autoArticles || [])[leftColumnCount].slug,
        }
      : null;

  const mostReadArticles = isManual
    ? manualMostReadItems
    : (autoArticles || []).slice(0, mostReadCount).map((a) => ({ title: a.title, linkUrl: a.slug }));

  return (
    <section className="w-full py-10" style={{ backgroundColor: bgColor || '#fefce8' }}>
      <div className="container max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        {isManual && (
          <div className="flex items-center gap-2 mb-4">
            <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-12 gap-6">
          {/* Left: Stacked thumbnails */}
          <div className="md:col-span-3 space-y-4">
            {loading
              ? Array.from({ length: leftColumnCount }).map((_, i) => (
                  <div key={i} className="rounded-xl overflow-hidden bg-slate-200 shadow-sm aspect-[4/3] animate-pulse" />
                ))
              : sideArticles.map((item, i) => (
                  <a key={i} href={item.linkUrl || '#'} className="block rounded-xl overflow-hidden shadow-sm hover:opacity-90 transition-opacity">
                    {item.image ? (
                      <img src={item.image} alt={item.title || ''} className="w-full aspect-[4/3] object-cover" />
                    ) : (
                      <div className="w-full aspect-[4/3] bg-slate-200 flex items-center justify-center text-slate-400 text-sm">📷 記事 {i + 1}</div>
                    )}
                  </a>
                ))}
          </div>

          {/* Center: Featured */}
          <div className="md:col-span-5 flex flex-col">
            {loading ? (
              <div className="rounded-xl overflow-hidden bg-slate-200 shadow-md flex-1 animate-pulse min-h-[300px]" />
            ) : featuredArticle ? (
              <a href={featuredArticle.linkUrl || '#'} className="block rounded-xl overflow-hidden shadow-md flex-1 min-h-[300px] hover:opacity-90 transition-opacity">
                {featuredArticle.image ? (
                  <img src={featuredArticle.image} alt={featuredArticle.title || ''} className="w-full h-full object-cover min-h-[300px]" />
                ) : (
                  <div className="w-full h-full bg-slate-200 flex items-center justify-center text-slate-400 text-sm min-h-[300px]">📷 注目記事</div>
                )}
              </a>
            ) : (
              <div className="rounded-xl overflow-hidden bg-slate-200 shadow-md flex-1 flex items-center justify-center text-slate-400 text-sm min-h-[300px]">📷 注目記事</div>
            )}
            {viewAllText && (
              <a
                href={viewAllUrl || '/blog'}
                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 mx-auto ${t.link} hover:opacity-80 transition-opacity`}
              >
                {viewAllText}
              </a>
            )}
          </div>

          {/* Right: Most Read list */}
          <div className="md:col-span-4">
            <h3 className={`text-lg font-bold mb-5 ${t.text}`}>{mostReadTitle}</h3>
            <div className="space-y-4">
              {loading
                ? Array.from({ length: mostReadCount }).map((_, i) => (
                    <div key={i} className="flex items-start gap-3 animate-pulse">
                      <span className={`text-lg font-black min-w-[2rem] text-center ${t.accent} opacity-60`}>{i + 1}</span>
                      <div className="h-4 bg-slate-200 rounded w-full" />
                    </div>
                  ))
                : mostReadArticles.map((item, i) => (
                    <a key={i} href={item.linkUrl || '#'} className="flex items-start gap-3 hover:opacity-70 transition-opacity">
                      <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 ${t.text}`}>{item.title || '(未入力)'}</h4>
                    </a>
                  ))}
            </div>
          </div>
        </div>
        <p className="text-center text-xs text-slate-400 mt-4 italic">
          {isManual ? '※ 手動モード' : '※ 自動モード — DBの最新記事を表示中'}
        </p>
      </div>
    </section>
  );
}
