import { getFirebaseAdmin } from '@/lib/firebase-admin';
import { getFirestore } from 'firebase-admin/firestore';

interface NewsletterUpdate {
  id: string;
  company_name: string;
  month_key: string;
  title: string;
  extracted_text: string;
  source: string;
  synced_at: Date;
}

async function getRecentUpdates(): Promise<NewsletterUpdate[]> {
  const app = getFirebaseAdmin();
  const db = getFirestore(app);

  // 최근 3개월 기준 날짜
  const threeMonthsAgo = new Date();
  threeMonthsAgo.setMonth(threeMonthsAgo.getMonth() - 3);

  const snapshot = await db
    .collection('newsletter_updates')
    .where('synced_at', '>=', threeMonthsAgo)
    .orderBy('synced_at', 'desc')
    .limit(50)
    .get();

  return snapshot.docs.map(doc => ({
    id: doc.id,
    ...doc.data(),
    synced_at: doc.data().synced_at?.toDate() || new Date(),
  })) as NewsletterUpdate[];
}

export default async function NewsletterUpdates() {
  const updates = await getRecentUpdates();

  if (updates.length === 0) {
    return (
      <div className="p-4 text-gray-500 text-sm">
        최근 소식지 업데이트가 없습니다.
      </div>
    );
  }

  // 보험사별 그룹화
  const grouped = updates.reduce((acc, update) => {
    if (!acc[update.company_name]) {
      acc[update.company_name] = [];
    }
    acc[update.company_name].push(update);
    return acc;
  }, {} as Record<string, NewsletterUpdate[]>);

  return (
    <div className="space-y-4">
      <h2 className="text-lg font-semibold text-gray-900">최근 소식지 업데이트</h2>
      {Object.entries(grouped)
        .sort(([a], [b]) => a.localeCompare(b))
        .map(([company, items]) => (
        <div key={company} className="border rounded-lg p-4">
          <h3 className="font-medium text-gray-800 mb-2">{company}</h3>
          <ul className="space-y-2">
            {items.map(item => (
              <li key={item.id} className="text-sm">
                <details>
                  <summary className="cursor-pointer hover:text-blue-600">
                    <span className="text-gray-500 mr-2">{item.month_key}</span>
                    {item.title}
                    <span className="text-xs text-gray-400 ml-2">
                      ({item.source === 'insuro_newsletter' ? '소식지' : '보험료'})
                    </span>
                  </summary>
                  <div className="mt-2 p-3 bg-gray-50 rounded text-xs text-gray-700 whitespace-pre-wrap max-h-96 overflow-y-auto">
                    {item.extracted_text}
                  </div>
                </details>
              </li>
            ))}
          </ul>
        </div>
      ))}
    </div>
  );
}
