'use client';
import React from 'react';
import { TrendingUp, Crown } from 'lucide-react';
import { useEditorData } from '@/hooks/useEditorData';
import type { Article } from '@/lib/utils/db';

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

interface ArticleGridTrendingRankingEditorProps {
  trendingTitle?: string;
  rankingTitle?: string;
  trendingCount?: number;
  rankingCount?: number;
  showTrending?: string;
  showRanking?: string;
  trendingMode?: string;
  rankingMode?: string;
  manualTrendingItems?: ManualItem[];
  manualRankingItems?: ManualItem[];
  theme?: string;
}

export function ArticleGridTrendingRankingEditor({
  trendingTitle = 'いま話題',
  rankingTitle = '人気記事ランキング',
  trendingCount = 5,
  rankingCount = 5,
  showTrending = 'yes',
  showRanking = 'yes',
  trendingMode = 'auto',
  rankingMode = 'auto',
  manualTrendingItems = [],
  manualRankingItems = [],
  theme = 'default',
}: ArticleGridTrendingRankingEditorProps) {
  const themeColors: Record<string, { accent: string; bg: string; badge: string; card: string; text: string; sub: string }> = {
    default: { accent: 'text-crimson-red', bg: 'bg-crimson-red', badge: 'bg-crimson-red text-white', card: 'bg-dark-gray border-soft-gray-border/20', text: 'text-white', sub: 'text-text-light-gray' },
    warm: { accent: 'text-orange-500', bg: 'bg-orange-500', badge: 'bg-orange-500 text-white', card: 'bg-white border-orange-200', text: 'text-slate-800', sub: 'text-slate-500' },
    professional: { accent: 'text-amber-400', bg: 'bg-amber-400', badge: 'bg-amber-400 text-slate-900', card: 'bg-slate-800 border-slate-700', text: 'text-white', sub: 'text-slate-400' },
    ocean: { accent: 'text-blue-500', bg: 'bg-blue-500', badge: 'bg-blue-500 text-white', card: 'bg-white border-blue-200', text: 'text-slate-800', sub: 'text-slate-500' },
    forest: { accent: 'text-emerald-500', bg: 'bg-emerald-500', badge: 'bg-emerald-500 text-white', card: 'bg-white border-emerald-200', text: 'text-slate-800', sub: 'text-slate-500' },
  };
  const tc = themeColors[theme] || themeColors.default;

  const isManualTrending = trendingMode === 'manual';
  const isManualRanking = rankingMode === 'manual';

  const { data: trendingArticles, loading: trendingLoading } = useEditorData<Article[]>({ type: 'trending', count: trendingCount, skip: isManualTrending });
  const { data: rankingArticles, loading: rankingLoading } = useEditorData<Article[]>({ type: 'latest', count: rankingCount, skip: isManualRanking });

  return (
    <section className="w-full py-10">
      <div className="container max-w-5xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
          {/* ─── Trending Column ─── */}
          {showTrending === 'yes' && (
            <div>
              <div className="flex items-center gap-2 mb-6">
                <TrendingUp className={`w-5 h-5 ${tc.accent}`} />
                <h2 className={`text-xl font-bold ${tc.text}`}>{trendingTitle}</h2>
                {isManualTrending && (
                  <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-4">
                {isManualTrending && manualTrendingItems.length > 0 ? (
                  manualTrendingItems.map((item, i) => (
                    <a key={i} href={item.linkUrl || '#'} className={`flex items-start gap-4 p-3 rounded-xl border ${tc.card} hover:opacity-80 transition-opacity`}>
                      <span className={`text-2xl font-black ${tc.accent} opacity-40 min-w-[2rem] text-center`}>{String(i + 1).padStart(2, '0')}</span>
                      <div className="flex-1 min-w-0">
                        <h3 className={`font-semibold text-sm leading-snug line-clamp-2 ${tc.text}`}>{item.title || '(タイトル未入力)'}</h3>
                        {item.linkUrl && <span className={`text-xs mt-1 block ${tc.sub} truncate`}>🔗 {item.linkUrl}</span>}
                      </div>
                    </a>
                  ))
                ) : isManualTrending && manualTrendingItems.length === 0 ? (
                  <div className={`p-4 rounded-xl border-2 border-dashed ${tc.card} text-center`}>
                    <p className={`text-sm ${tc.sub}`}>「Manual Trending Items」にアイテムを追加してください</p>
                  </div>
                ) : trendingLoading ? (
                  Array.from({ length: trendingCount }).map((_, i) => (
                    <div key={i} className={`flex items-start gap-4 p-3 rounded-xl border ${tc.card} animate-pulse`}>
                      <span className={`text-2xl font-black ${tc.accent} opacity-40 min-w-[2rem] text-center`}>{String(i + 1).padStart(2, '0')}</span>
                      <div className="flex-1"><div className="h-4 bg-slate-200 rounded w-3/4 mb-2" /><div className="h-3 bg-slate-100 rounded w-1/3" /></div>
                    </div>
                  ))
                ) : (
                  (trendingArticles || []).map((article, i) => (
                    <a key={i} href={article.slug} className={`flex items-start gap-4 p-3 rounded-xl border ${tc.card} hover:opacity-80 transition-opacity`}>
                      <span className={`text-2xl font-black ${tc.accent} opacity-40 min-w-[2rem] text-center`}>{String(i + 1).padStart(2, '0')}</span>
                      <div className="flex-1 min-w-0">
                        <h3 className={`font-semibold text-sm leading-snug line-clamp-2 ${tc.text}`}>{article.title}</h3>
                        {article.category && <span className={`text-xs mt-1 block ${tc.sub}`}>{article.category}</span>}
                      </div>
                    </a>
                  ))
                )}
              </div>
            </div>
          )}

          {/* ─── Ranking Column ─── */}
          {showRanking === 'yes' && (
            <div>
              <div className="flex items-center gap-2 mb-6">
                <Crown className={`w-5 h-5 ${tc.accent}`} />
                <h2 className={`text-xl font-bold ${tc.text}`}>{rankingTitle}</h2>
                {isManualRanking && (
                  <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-3">
                {isManualRanking && manualRankingItems.length > 0 ? (
                  manualRankingItems.map((item, i) => (
                    <a key={i} href={item.linkUrl || '#'} className={`flex items-center gap-3 p-3 rounded-xl border ${tc.card} hover:opacity-80 transition-opacity`}>
                      <span className={`w-8 h-8 rounded-full ${i < 3 ? tc.badge : 'bg-slate-200 text-slate-500'} flex items-center justify-center text-sm font-bold shrink-0`}>{i + 1}</span>
                      {item.image ? (
                        <img src={item.image} alt={item.title || ''} className="w-16 h-12 object-cover rounded-lg shrink-0" />
                      ) : (
                        <div className="w-16 h-12 bg-slate-200 rounded-lg shrink-0 flex items-center justify-center text-slate-400 text-[10px]">📷</div>
                      )}
                      <div className="flex-1 min-w-0">
                        <h3 className={`font-medium text-sm line-clamp-2 ${tc.text}`}>{item.title || '(タイトル未入力)'}</h3>
                        {item.linkUrl && <span className={`text-xs block ${tc.sub} truncate`}>🔗 {item.linkUrl}</span>}
                      </div>
                    </a>
                  ))
                ) : isManualRanking && manualRankingItems.length === 0 ? (
                  <div className={`p-4 rounded-xl border-2 border-dashed ${tc.card} text-center`}>
                    <p className={`text-sm ${tc.sub}`}>「Manual Ranking Items」にアイテムを追加してください</p>
                  </div>
                ) : rankingLoading ? (
                  Array.from({ length: rankingCount }).map((_, i) => (
                    <div key={i} className={`flex items-center gap-3 p-3 rounded-xl border ${tc.card} animate-pulse`}>
                      <span className={`w-8 h-8 rounded-full ${i < 3 ? tc.badge : 'bg-slate-200 text-slate-500'} flex items-center justify-center text-sm font-bold`}>{i + 1}</span>
                      <div className="w-16 h-12 bg-slate-200 rounded-lg shrink-0" />
                      <div className="h-4 bg-slate-200 rounded w-2/3 flex-1" />
                    </div>
                  ))
                ) : (
                  (rankingArticles || []).map((article, i) => (
                    <a key={i} href={article.slug} className={`flex items-center gap-3 p-3 rounded-xl border ${tc.card} hover:opacity-80 transition-opacity`}>
                      <span className={`w-8 h-8 rounded-full ${i < 3 ? tc.badge : 'bg-slate-200 text-slate-500'} flex items-center justify-center text-sm font-bold shrink-0`}>{i + 1}</span>
                      {article.cardImage ? (
                        <img src={article.cardImage} alt={article.title} className="w-16 h-12 object-cover rounded-lg shrink-0" />
                      ) : (
                        <div className="w-16 h-12 bg-slate-200 rounded-lg shrink-0 flex items-center justify-center text-slate-400 text-[10px]">📷</div>
                      )}
                      <div className="flex-1 min-w-0">
                        <h3 className={`font-medium text-sm line-clamp-2 ${tc.text}`}>{article.title}</h3>
                        {article.category && <span className={`text-xs block ${tc.sub}`}>{article.category}</span>}
                      </div>
                    </a>
                  ))
                )}
              </div>
            </div>
          )}
        </div>
        <p className="text-center text-xs text-text-light-gray mt-4 italic">
          {isManualTrending || isManualRanking
            ? '※ 手動モード — 上記のアイテムがそのまま公開ページに表示されます'
            : '※ 自動モード — 実際のページでは最新の記事がデータベースから表示されます'}
        </p>
      </div>
    </section>
  );
}
