'use client';

import { useMemo } from 'react';
import { useRouter } from 'next/navigation';
import { CreditCard, Wallet, Receipt, AlertTriangle, Gift, CheckCircle2, ShieldAlert } from 'lucide-react';
import { formatKoreanAmount } from '@/lib/utils/amount';
import { AmountCardItem, CheckPointItem, CollapsibleDashboardCard, type SectionColorTheme } from '../components';
import type { CardManagementData } from '../types';

// 카드별 아이콘 매핑
const CARD_ICONS = [CreditCard, Gift, Receipt, AlertTriangle, Wallet];
const CARD_THEMES: SectionColorTheme[] = ['blue', 'indigo', 'purple', 'orange', 'blue'];

interface CardManagementSectionProps {
  data: CardManagementData;
  onCardClick?: (cardId: string) => void;
}

/** subLabel에서 "미정리 N건", "미증빙 N건" 등의 건수를 파싱 */
function parseIssueCount(subLabel?: string): number {
  if (!subLabel) return 0;
  const match = subLabel.match(/(\d+)\s*건/);
  return match ? parseInt(match[1], 10) : 0;
}

export function CardManagementSection({ data, onCardClick }: CardManagementSectionProps) {
  const router = useRouter();

  // 카드별 미정리/미증빙 건수 집계
  const issueStats = useMemo(() => {
    let totalCount = 0;
    let totalAmount = 0;
    const issueCards: string[] = [];

    for (const card of data.cards) {
      const count = parseIssueCount(card.subLabel);
      if (count > 0 || card.isHighlighted) {
        totalCount += count;
        totalAmount += card.subAmount ?? 0;
        issueCards.push(card.label);
      }
    }
    return { totalCount, totalAmount, issueCards, hasIssues: totalCount > 0 };
  }, [data.cards]);

  const handleClick = (cardId: string) => {
    if (onCardClick) {
      onCardClick(cardId);
    } else {
      router.push('/ko/accounting/card-management');
    }
  };

  return (
    <CollapsibleDashboardCard
      icon={<CreditCard style={{ color: '#ffffff' }} className="h-5 w-5" />}
      title="가지급금 현황"
      subtitle="가지급금 관리 현황"
    >
      {/* 상태 배너: 미정리 있으면 빨간 펄스, 정상이면 초록 */}
      {issueStats.hasIssues ? (
        <div className="relative overflow-hidden rounded-lg mb-4">
          {/* 펄스 배경 */}
          <div className="absolute inset-0 bg-red-500 animate-pulse opacity-20 rounded-lg" />
          <div className="relative bg-red-50 dark:bg-red-900/40 border border-red-300 dark:border-red-700 px-4 py-3 rounded-lg flex items-center justify-between gap-3">
            <div className="flex items-center gap-2.5">
              <div className="w-8 h-8 rounded-full bg-red-500 flex items-center justify-center shrink-0">
                <ShieldAlert className="h-4 w-4 text-white" />
              </div>
              <div>
                <p className="text-sm font-bold text-red-700 dark:text-red-300">
                  미정리 {issueStats.totalCount}건
                </p>
                <p className="text-xs text-red-600/80 dark:text-red-400/80">
                  {issueStats.issueCards.join(' · ')}
                </p>
              </div>
            </div>
            {issueStats.totalAmount > 0 && (
              <div className="text-right shrink-0">
                <p className="text-lg font-bold text-red-700 dark:text-red-300">
                  {formatKoreanAmount(issueStats.totalAmount)}
                </p>
                <p className="text-[11px] text-red-500/70 dark:text-red-400/60">미정리 총액</p>
              </div>
            )}
          </div>
        </div>
      ) : (
        <div className="bg-green-50 dark:bg-green-900/30 border border-green-200 dark:border-green-800 px-4 py-2.5 rounded-lg mb-4 flex items-center gap-2.5">
          <CheckCircle2 className="h-4 w-4 text-green-500" />
          <span className="text-sm font-medium text-green-700 dark:text-green-300">미정리 건 없음 — 가지급금 정상 관리 중</span>
        </div>
      )}

      {/* 기존 warningBanner 호환 (issueStats과 별도 메시지가 있는 경우) */}
      {data.warningBanner && issueStats.hasIssues && (
        <div className="bg-amber-50 dark:bg-amber-900/30 border border-amber-200 dark:border-amber-800 text-amber-700 dark:text-amber-300 text-xs font-medium px-3 py-2 rounded-lg mb-4 flex items-center gap-2">
          <AlertTriangle className="h-3.5 w-3.5" />
          {data.warningBanner}
        </div>
      )}

      <div className="grid grid-cols-1 xs:grid-cols-2 md:grid-cols-5 gap-3 xs:gap-4 mb-4">
        {data.cards.map((card, idx) => (
          <AmountCardItem
            key={card.id}
            card={card}
            onClick={() => handleClick(card.id)}
            icon={CARD_ICONS[idx] || CreditCard}
            colorTheme={CARD_THEMES[idx] || 'blue'}
            showTrend={!!card.previousLabel}
            trendValue={card.previousLabel}
            trendDirection="up"
          />
        ))}
      </div>

      {data.checkPoints.length > 0 && (
        <div className="border-t pt-4 space-y-1">
          {data.checkPoints.map((cp) => (
            <CheckPointItem key={cp.id} checkpoint={cp} />
          ))}
        </div>
      )}
    </CollapsibleDashboardCard>
  );
}
