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

interface ManualTrendItem {
  title?: string;
  linkUrl?: string;
}

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

interface TwoColumnLayoutEditorProps {
  trendTitle?: string;
  mostReadTitle?: string;
  theme?: string;
  trendDataMode?: string;
  mostReadDataMode?: string;
  manualTrendItems?: ManualTrendItem[];
  manualMostReadItems?: ManualMostReadItem[];
}

export function TwoColumnLayoutEditor({
  trendTitle = 'トレンド記事',
  mostReadTitle = 'よく読まれている記事',
  theme = 'default',
  trendDataMode = 'auto',
  mostReadDataMode = 'auto',
  manualTrendItems = [],
  manualMostReadItems = [],
}: TwoColumnLayoutEditorProps) {
  const isManualTrend = trendDataMode === 'manual';
  const isManualMostRead = mostReadDataMode === 'manual';

  // Fetch real DB data for auto mode
  const { data: trendingArticles, loading: trendLoading } = useEditorData<Article[]>({
    type: 'trending',
    count: 5,
    skip: isManualTrend,
  });
  const { data: mostReadArticles, loading: mostReadLoading } = useEditorData<Article[]>({
    type: 'latest',
    count: 5,
    skip: isManualMostRead,
  });

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

  // Build display arrays
  const trendDisplay = isManualTrend
    ? manualTrendItems.map((item) => ({ title: item.title || '(未入力)', href: item.linkUrl || '#' }))
    : (trendingArticles || []).map((a) => ({ title: a.title, href: a.slug }));

  const mostReadDisplay = isManualMostRead
    ? manualMostReadItems.map((item) => ({ title: item.title || '(未入力)', image: item.image || '', href: item.linkUrl || '#' }))
    : (mostReadArticles || []).map((a) => ({ title: a.title, image: a.cardImage || '', href: a.slug }));

  return (
    <section className="w-full py-10">
      <div className="container max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
          {/* Trending Widget */}
          <div className={`border rounded-2xl p-6 shadow-sm ${tc.card}`}>
            <div className="flex items-center gap-2 mb-5">
              <TrendingUp className={`w-5 h-5 ${tc.accent}`} />
              <h3 className={`font-bold text-lg ${tc.text}`}>{trendTitle}</h3>
              {isManualTrend && <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">
              {trendLoading && !isManualTrend ? (
                Array.from({ length: 5 }, (_, i) => (
                  <div key={i} className="flex items-center gap-3 p-2.5 animate-pulse">
                    <span className={`text-lg font-black ${tc.accent} opacity-30 w-6 text-center`}>{i + 1}</span>
                    <div className="h-4 bg-slate-200 rounded flex-1" />
                  </div>
                ))
              ) : isManualTrend && manualTrendItems.length === 0 ? (
                <div className="p-4 rounded-lg border-2 border-dashed border-slate-300 text-center">
                  <p className={`text-sm ${tc.sub}`}>「Manual Trend Items」にアイテムを追加してください</p>
                </div>
              ) : trendDisplay.length === 0 ? (
                <p className={`text-sm ${tc.sub} text-center py-4`}>記事がありません</p>
              ) : (
                trendDisplay.map((item, i) => (
                  <a
                    key={i}
                    href={item.href}
                    className={`flex items-center gap-3 p-2.5 rounded-lg hover:bg-black/5 transition-colors`}
                  >
                    <span className={`text-lg font-black ${tc.accent} opacity-30 w-6 text-center`}>{i + 1}</span>
                    <div className="flex-1 min-w-0">
                      <h4 className={`text-sm font-medium line-clamp-2 leading-snug ${tc.text}`}>{item.title}</h4>
                    </div>
                  </a>
                ))
              )}
            </div>
          </div>

          {/* Most Read Widget */}
          <div className={`border rounded-2xl p-6 shadow-sm ${tc.card}`}>
            <div className="flex items-center gap-2 mb-5">
              <BookOpen className={`w-5 h-5 ${tc.accent}`} />
              <h3 className={`font-bold text-lg ${tc.text}`}>{mostReadTitle}</h3>
              {isManualMostRead && <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">
              {mostReadLoading && !isManualMostRead ? (
                Array.from({ length: 5 }, (_, i) => (
                  <div key={i} className="flex items-center gap-3 p-2.5 animate-pulse">
                    <div className="w-14 h-10 bg-slate-200 rounded-md shrink-0" />
                    <div className="h-4 bg-slate-200 rounded flex-1" />
                  </div>
                ))
              ) : isManualMostRead && manualMostReadItems.length === 0 ? (
                <div className="p-4 rounded-lg border-2 border-dashed border-slate-300 text-center">
                  <p className={`text-sm ${tc.sub}`}>「Manual Most Read Items」にアイテムを追加してください</p>
                </div>
              ) : mostReadDisplay.length === 0 ? (
                <p className={`text-sm ${tc.sub} text-center py-4`}>記事がありません</p>
              ) : (
                mostReadDisplay.map((item, i) => (
                  <a
                    key={i}
                    href={item.href}
                    className={`flex items-center gap-3 p-2.5 rounded-lg hover:bg-black/5 transition-colors`}
                  >
                    {item.image ? (
                      <img src={item.image} alt={item.title} className="w-14 h-10 object-cover rounded-md shrink-0" />
                    ) : (
                      <div className="w-14 h-10 bg-slate-200 rounded-md shrink-0 flex items-center justify-center text-slate-400 text-[10px]">📷</div>
                    )}
                    <div className="flex-1 min-w-0">
                      <h4 className={`text-sm font-medium line-clamp-2 leading-snug ${tc.text}`}>{item.title}</h4>
                    </div>
                  </a>
                ))
              )}
            </div>
          </div>
        </div>
        <p className="text-center text-xs text-text-light-gray mt-4 italic">
          {isManualTrend || isManualMostRead
            ? '※ 手動モード — 上記のアイテムがそのまま公開ページに表示されます'
            : '※ 自動モード — DBの記事を表示中'}
        </p>
      </div>
    </section>
  );
}
