'use client';
import React from 'react';
import { ChevronRight, LayoutGrid } from 'lucide-react';
import { useEditorData } from '@/hooks/useEditorData';

interface ManualArticle {
  title?: string;
  image?: string;
  linkUrl?: string;
}

interface ManualCategory {
  categoryName?: string;
  articles?: ManualArticle[];
}

interface ArticleGridCategorySectionsEditorProps {
  articlesPerCategory?: number;
  showViewMore?: string;
  theme?: string;
  dataMode?: string;
  manualCategories?: ManualCategory[];
}

export function ArticleGridCategorySectionsEditor({
  articlesPerCategory = 4,
  showViewMore = 'yes',
  theme = 'default',
  dataMode = 'auto',
  manualCategories = [],
}: ArticleGridCategorySectionsEditorProps) {
  const isManual = dataMode === 'manual';

  const { data: autoCategories, loading } = useEditorData<any[]>({
    type: 'categories-with-articles',
    count: articlesPerCategory,
    skip: isManual,
  });

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

  const displayCategories = isManual
    ? manualCategories
    : (autoCategories || []);

  return (
    <section className={`w-full py-10 ${bgClass}`}>
      <div className="container max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 space-y-12">
        {loading && !isManual ? (
          /* Auto mode loading skeleton */
          Array.from({ length: 2 }, (_, ci) => (
            <div key={ci} className="animate-pulse">
              <div className="flex items-center justify-between mb-6">
                <div className="flex items-center gap-3">
                  <div className="h-6 bg-slate-200 rounded w-32" />
                  <span className={`text-xs px-2 py-0.5 rounded-full ${t.badge} text-white font-medium`}>...記事</span>
                </div>
              </div>
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
                {Array.from({ length: articlesPerCategory }, (_, ai) => (
                  <div key={ai} className={`${t.cardBg} rounded-xl border ${t.border} overflow-hidden block`}>
                    <div className="aspect-[16/9] bg-slate-200 flex items-center justify-center text-slate-400 text-sm">📷</div>
                    <div className="p-3">
                      <div className="h-4 bg-slate-200 rounded w-3/4 mb-1" />
                      <div className="h-3 bg-slate-100 rounded w-1/3" />
                    </div>
                  </div>
                ))}
              </div>
            </div>
          ))
        ) : displayCategories.length > 0 ? (
          /* Render categories */
          displayCategories.map((mc, ci) => (
            <div key={ci}>
              <div className="flex items-center justify-between mb-6">
                <div className="flex items-center gap-3">
                  <h2 className={`text-xl font-bold ${t.text}`}>{mc.categoryName || '未分類'}</h2>
                  <span className={`text-xs px-2 py-0.5 rounded-full ${t.badge} text-white font-medium`}>
                    {mc.articles?.length || 0}記事
                  </span>
                  {isManual && (
                    <span className="text-[10px] px-2 py-0.5 bg-amber-100 text-amber-700 rounded-full font-medium">手動</span>
                  )}
                </div>
                {!isManual && showViewMore === 'yes' && (
                  <span className={`flex items-center gap-1 text-sm font-medium ${t.accent}`}>
                    すべて見る <ChevronRight className="w-4 h-4" />
                  </span>
                )}
              </div>
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
                {(mc.articles || []).map((article: any, ai: number) => (
                  <a
                    key={ai}
                    href={article.linkUrl || '#'}
                    className={`${t.cardBg} rounded-xl border ${t.border} overflow-hidden hover:opacity-90 hover:shadow-sm transition-all block`}
                  >
                    <div className="aspect-[16/9] bg-slate-200 relative">
                      {article.image ? (
                        <img src={article.image} alt={article.title || ''} className="w-full h-full object-cover" />
                      ) : (
                        <div className="w-full h-full flex items-center justify-center text-slate-400 text-sm">📷</div>
                      )}
                    </div>
                    <div className="p-3">
                      <h3 className={`font-semibold text-sm line-clamp-2 leading-snug ${t.text}`}>
                        {article.title || '(タイトル未入力)'}
                      </h3>
                    </div>
                  </a>
                ))}
              </div>
            </div>
          ))
        ) : isManual ? (
          <div className="p-8 rounded-xl border-2 border-dashed border-slate-300 text-center">
            <LayoutGrid className="w-8 h-8 text-slate-400 mx-auto mb-3" />
            <p className="text-sm text-text-light-gray">「Manual Categories」にカテゴリーと記事を追加してください</p>
          </div>
        ) : (
          <div className="p-8 rounded-xl border-2 border-dashed border-slate-300 text-center">
            <LayoutGrid className="w-8 h-8 text-slate-400 mx-auto mb-3" />
            <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>
  );
}
