'use client';

import {
  Wallet,
  TrendingUp,
  AlertTriangle,
  CheckCircle2,
  Clock,
  Users,
  FileText,
  ShoppingCart,
  Building2,
  Calendar,
  CreditCard,
  Receipt,
  Briefcase,
  AlertCircle,
  Banknote,
  CircleDollarSign,
  LayoutGrid,
  type LucideIcon,
} from 'lucide-react';
import { useRouter } from 'next/navigation';
import { Badge } from '@/components/ui/badge';
import { formatKoreanAmount } from '@/lib/utils/amount';
import { CollapsibleDashboardCard } from '../components';
import type { DailyReportData, MonthlyExpenseData, TodayIssueItem, TodayIssueSettings } from '../types';

// ============================================================
// 유틸리티 함수
// ============================================================

const formatUSD = (amount: number): string => {
  return '$ ' + new Intl.NumberFormat('en-US').format(amount);
};

// ============================================================
// 강화된 일일 일보 섹션
// ============================================================

interface EnhancedDailyReportSectionProps {
  data: DailyReportData;
  onClick?: () => void;
  onExpenseDetailClick?: () => void;
}

const CARD_STYLES = [
  { bgClass: 'bg-emerald-50 dark:bg-emerald-900/30', borderClass: 'border-emerald-200 dark:border-emerald-800', iconBg: '#10b981', labelClass: 'text-emerald-700 dark:text-emerald-300', Icon: FileText },
  { bgClass: 'bg-blue-50 dark:bg-blue-900/30', borderClass: 'border-blue-200 dark:border-blue-800', iconBg: '#3b82f6', labelClass: 'text-blue-700 dark:text-blue-300', Icon: Receipt },
  { bgClass: 'bg-purple-50 dark:bg-purple-900/30', borderClass: 'border-purple-200 dark:border-purple-800', iconBg: '#8b5cf6', labelClass: 'text-purple-700 dark:text-purple-300', Icon: Briefcase },
  { bgClass: 'bg-orange-50 dark:bg-orange-900/30', borderClass: 'border-orange-200 dark:border-orange-800', iconBg: '#f97316', labelClass: 'text-orange-700 dark:text-orange-300', Icon: Clock },
];

export function EnhancedDailyReportSection({ data, onClick, onExpenseDetailClick }: EnhancedDailyReportSectionProps) {
  const router = useRouter();

  const handleCardClick = (card: DailyReportData['cards'][number]) => {
    // dr3 (미지급금 잔액): 클릭 동작 없음
    if (card.id === 'dr3') return;
    // dr4 (당월 예상 지출 합계): 상세 팝업 표시
    if (card.id === 'dr4') {
      onExpenseDetailClick?.();
      return;
    }
    // dr1, dr2: path로 페이지 이동
    if (card.path) {
      router.push(card.path);
    } else if (onClick) {
      onClick();
    }
  };

  return (
    <CollapsibleDashboardCard
      icon={<Wallet style={{ color: '#ffffff' }} className="h-5 w-5" />}
      title="자금현황"
      subtitle={data.date}
      rightElement={
        <Badge
          style={{ backgroundColor: '#10b981', color: '#ffffff', border: 'none' }}
          className="hover:opacity-90"
        >
          실시간
        </Badge>
      }
    >
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
          {data.cards.map((card, idx) => {
            const style = CARD_STYLES[idx] || CARD_STYLES[0];
            const CardIcon = style.Icon;
            return (
              <div
                key={card.id}
                className={`rounded-xl p-4 transition-all border min-h-[110px] flex flex-col ${style.bgClass} ${style.borderClass} ${card.id === 'dr3' ? 'cursor-default' : 'cursor-pointer hover:shadow-lg'}`}
                onClick={() => handleCardClick(card)}
              >
                <div className="flex items-center gap-2 mb-3">
                  <div style={{ backgroundColor: style.iconBg }} className="p-1.5 rounded-lg">
                    <CardIcon className="h-4 w-4 text-white" />
                  </div>
                  <span className={`text-sm font-medium ${style.labelClass}`}>
                    {card.label}
                  </span>
                </div>
                <div className="text-2xl font-bold text-foreground">
                  {card.displayValue
                    ? card.displayValue
                    : card.currency === 'USD'
                      ? formatUSD(card.amount)
                      : formatKoreanAmount(card.amount)}
                </div>
                {/* 기획서 D1.7 기준: 자금현황 카드에 전일 대비 미표시 — 추후 필요 시 복원
                {card.changeRate && (
                  <div className="flex items-center gap-1 px-2 py-1 rounded-full text-xs font-semibold mt-auto w-fit bg-green-100 text-green-700 dark:bg-green-900/40 dark:text-green-300">
                    <TrendingUp className="h-3 w-3" />
                    전일 대비 {card.changeRate}
                  </div>
                )}
                */}
              </div>
            );
          })}
        </div>

        {/* 체크포인트 */}
        {data.checkPoints.length > 0 && (
          <div className="space-y-2">
            <p className="text-xs font-medium uppercase tracking-wider mb-3 text-muted-foreground">주요 알림</p>
            {data.checkPoints.map((cp, idx) => (
              <div
                key={cp.id}
                className={`flex items-start gap-3 p-3 rounded-lg border ${idx === 0 ? 'bg-amber-50 border-amber-200 dark:bg-amber-900/30 dark:border-amber-800' : 'bg-slate-50 border-slate-200 dark:bg-slate-800 dark:border-slate-700'}`}
              >
                <div
                  className={`p-1 rounded-full shrink-0 ${idx === 0 ? 'bg-amber-100 dark:bg-amber-800' : 'bg-slate-100 dark:bg-slate-700'}`}
                >
                  {idx === 0 ? (
                    <AlertTriangle className="h-4 w-4 text-amber-600 dark:text-amber-400" />
                  ) : (
                    <CheckCircle2 className="h-4 w-4 text-green-600 dark:text-green-400" />
                  )}
                </div>
                <p className="text-sm flex-1 text-muted-foreground">{cp.message}</p>
              </div>
            ))}
          </div>
        )}
    </CollapsibleDashboardCard>
  );
}

// ============================================================
// 강화된 현황판 섹션
// ============================================================

// 라벨 → 설정키 매핑
const LABEL_TO_SETTING_KEY: Record<string, keyof TodayIssueSettings> = {
  '수주': 'orders',
  '채권 추심': 'debtCollection',
  '안전 재고': 'safetyStock',
  '세금 신고': 'taxReport',
  '신규 업체 등록': 'newVendor',
  '연차': 'annualLeave',
  '차량': 'vehicle',
  '장비': 'equipment',
  '발주': 'purchase',
  '결재 요청': 'approvalRequest',
};

// 라벨별 스타일 매핑 (Tailwind 클래스 기반 - 다크모드 지원)
const ITEM_STYLES: Record<string, { bgClass: string; borderClass: string; iconBg: string; labelClass: string; Icon: React.ComponentType<{ style?: React.CSSProperties; className?: string }> }> = {
  '수주': { bgClass: 'bg-blue-50 dark:bg-blue-900/30', borderClass: 'border-blue-200 dark:border-blue-800', iconBg: '#3b82f6', labelClass: 'text-blue-700 dark:text-blue-300', Icon: ShoppingCart },
  '채권 추심': { bgClass: 'bg-red-50 dark:bg-red-900/30', borderClass: 'border-red-200 dark:border-red-800', iconBg: '#ef4444', labelClass: 'text-red-700 dark:text-red-300', Icon: AlertCircle },
  '안전 재고': { bgClass: 'bg-orange-50 dark:bg-orange-900/30', borderClass: 'border-orange-200 dark:border-orange-800', iconBg: '#f97316', labelClass: 'text-orange-700 dark:text-orange-300', Icon: Receipt },
  '세금 신고': { bgClass: 'bg-purple-50 dark:bg-purple-900/30', borderClass: 'border-purple-200 dark:border-purple-800', iconBg: '#a855f7', labelClass: 'text-purple-700 dark:text-purple-300', Icon: FileText },
  '신규 업체 등록': { bgClass: 'bg-emerald-50 dark:bg-emerald-900/30', borderClass: 'border-emerald-200 dark:border-emerald-800', iconBg: '#10b981', labelClass: 'text-emerald-700 dark:text-emerald-300', Icon: Building2 },
  '연차': { bgClass: 'bg-cyan-50 dark:bg-cyan-900/30', borderClass: 'border-cyan-200 dark:border-cyan-800', iconBg: '#06b6d4', labelClass: 'text-cyan-700 dark:text-cyan-300', Icon: Calendar },
  '지각': { bgClass: 'bg-amber-50 dark:bg-amber-900/30', borderClass: 'border-amber-200 dark:border-amber-800', iconBg: '#f59e0b', labelClass: 'text-amber-700 dark:text-amber-300', Icon: Clock },
  '결근': { bgClass: 'bg-rose-50 dark:bg-rose-900/30', borderClass: 'border-rose-200 dark:border-rose-800', iconBg: '#f43f5e', labelClass: 'text-rose-700 dark:text-rose-300', Icon: Users },
  '발주': { bgClass: 'bg-indigo-50 dark:bg-indigo-900/30', borderClass: 'border-indigo-200 dark:border-indigo-800', iconBg: '#6366f1', labelClass: 'text-indigo-700 dark:text-indigo-300', Icon: Briefcase },
  '결재 요청': { bgClass: 'bg-pink-50 dark:bg-pink-900/30', borderClass: 'border-pink-200 dark:border-pink-800', iconBg: '#ec4899', labelClass: 'text-pink-700 dark:text-pink-300', Icon: CheckCircle2 },
};

const DEFAULT_STYLE = { bgClass: 'bg-slate-50 dark:bg-slate-800', borderClass: 'border-slate-200 dark:border-slate-700', iconBg: '#64748b', labelClass: 'text-slate-600 dark:text-slate-400', Icon: FileText };

interface EnhancedStatusBoardSectionProps {
  items: TodayIssueItem[];
  itemSettings?: TodayIssueSettings;
}

export function EnhancedStatusBoardSection({ items, itemSettings }: EnhancedStatusBoardSectionProps) {
  const router = useRouter();

  const handleItemClick = (path: string) => {
    if (!path) return;
    router.push(path);
  };

  // 설정에 따라 항목 필터링
  const filteredItems = itemSettings
    ? items.filter((item) => {
        const settingKey = LABEL_TO_SETTING_KEY[item.label];
        return settingKey ? itemSettings[settingKey] : true;
      })
    : items;

  return (
    <CollapsibleDashboardCard
      icon={<LayoutGrid style={{ color: '#ffffff' }} className="h-5 w-5" />}
      title="현황판"
      subtitle="주요 현황 요약"
      rightElement={
        <Badge
          style={{ backgroundColor: '#f59e0b', color: '#ffffff', border: 'none' }}
        >
          {filteredItems.length}개 항목
        </Badge>
      }
    >
        {/* 카드 그리드 */}
        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-3">
          {filteredItems.map((item) => {
            const isHighlighted = item.isHighlighted;
            const style = ITEM_STYLES[item.label] || DEFAULT_STYLE;
            const Icon = style.Icon;

            return (
              <div
                key={item.id}
                className={`relative p-4 rounded-xl border transition-all min-h-[130px] flex flex-col ${item.path ? 'cursor-pointer hover:scale-[1.02] hover:shadow-md' : 'cursor-default'} ${isHighlighted ? 'bg-red-500 border-red-500 dark:bg-red-600 dark:border-red-600' : `${style.bgClass} ${style.borderClass}`}`}
                onClick={() => handleItemClick(item.path)}
              >
                {/* 아이콘 + 라벨 */}
                <div className="flex items-center gap-2 mb-3 min-w-0">
                  <div
                    className="p-1.5 rounded-lg shrink-0"
                    style={{ backgroundColor: isHighlighted ? 'rgba(255,255,255,0.2)' : style.iconBg }}
                  >
                    <Icon className="h-4 w-4 text-white" />
                  </div>
                  <span className={`text-sm font-medium truncate flex-1 min-w-0 ${isHighlighted ? 'text-white' : style.labelClass}`}>
                    {item.label}
                  </span>
                </div>

                {/* 숫자 */}
                <div className={`text-2xl font-bold ${isHighlighted ? 'text-white' : 'text-foreground'}`}>
                  {typeof item.count === 'number' ? `${item.count}건` : item.count}
                </div>

                {/* 부가 정보 (최근 항목 외 N건) - pill 뱃지 스타일 */}
                {item.subLabel && (
                  <span
                    className={`text-xs font-medium mt-auto px-2 py-0.5 rounded-full border truncate w-fit max-w-full ${isHighlighted ? 'bg-white/20 text-white border-white/30' : style.labelClass}`}
                    style={!isHighlighted ? {
                      backgroundColor: `${style.iconBg}15`,
                      borderColor: `${style.iconBg}30`,
                    } : undefined}
                  >
                    {item.subLabel}
                  </span>
                )}
              </div>
            );
          })}
        </div>
    </CollapsibleDashboardCard>
  );
}

// ============================================================
// 강화된 당월 예상 지출 섹션
// ============================================================

interface EnhancedMonthlyExpenseSectionProps {
  data: MonthlyExpenseData;
  onCardClick?: (cardId: string) => void;
}

// 당월 예상 지출 카드 설정
const EXPENSE_CARD_CONFIGS: Array<{
  icon: LucideIcon;
  iconBg: string;
  bgClass: string;
  labelClass: string;
  defaultLabel: string;
  defaultId: string;
}> = [
  { icon: Receipt, iconBg: '#8b5cf6', bgClass: 'bg-purple-50 border-purple-200 dark:bg-purple-900/30 dark:border-purple-800', labelClass: 'text-purple-700 dark:text-purple-300', defaultLabel: '매입', defaultId: 'me1' },
  { icon: CreditCard, iconBg: '#3b82f6', bgClass: 'bg-blue-50 border-blue-200 dark:bg-blue-900/30 dark:border-blue-800', labelClass: 'text-blue-700 dark:text-blue-300', defaultLabel: '카드', defaultId: 'me2' },
  { icon: Banknote, iconBg: '#f59e0b', bgClass: 'bg-amber-50 border-amber-200 dark:bg-amber-900/30 dark:border-amber-800', labelClass: 'text-amber-700 dark:text-amber-300', defaultLabel: '발행어음', defaultId: 'me3' },
];

export function EnhancedMonthlyExpenseSection({ data, onCardClick }: EnhancedMonthlyExpenseSectionProps) {
  // 총 예상 지출: cards[3]이 API total_amount (advance 등 미표시 항목 포함)
  const totalAmount = Number(data.cards[3]?.amount) || 0;

  return (
    <CollapsibleDashboardCard
      icon={<Receipt className="h-5 w-5 text-white" />}
      title="당월 예상 지출 내역"
      subtitle="이달 예상 지출 정보"
      rightElement={undefined}
    >
        {/* 카드 그리드 */}
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
          {EXPENSE_CARD_CONFIGS.map((config, idx) => {
            const card = data.cards[idx];
            const CardIcon = config.icon;
            return (
              <div
                key={config.defaultId}
                className={`rounded-xl p-4 cursor-pointer transition-all hover:scale-[1.02] hover:shadow-lg border min-h-[130px] flex flex-col ${config.bgClass}`}
                onClick={() => onCardClick?.(card?.id || config.defaultId)}
              >
                <div className="flex items-center gap-2 mb-2">
                  <div style={{ backgroundColor: config.iconBg }} className="p-1.5 rounded-lg">
                    <CardIcon className="h-4 w-4 text-white" />
                  </div>
                  <span className={`text-sm font-medium ${config.labelClass}`}>
                    {card?.label || config.defaultLabel}
                  </span>
                </div>
                <div className="text-2xl font-bold text-foreground">
                  {formatKoreanAmount(card?.amount || 0)}
                </div>
                {card?.previousLabel && (
                  <div className="flex items-center gap-1 px-2 py-1 rounded-full text-xs font-semibold mt-auto w-fit bg-green-100 text-green-700 dark:bg-green-900/40 dark:text-green-300">
                    <TrendingUp className="h-3 w-3" />
                    {card.previousLabel}
                  </div>
                )}
              </div>
            );
          })}

          {/* 카드 4: 총 예상 지출 합계 (강조) */}
          <div
            className="rounded-xl p-4 cursor-pointer transition-all hover:scale-[1.02] hover:shadow-lg border min-h-[130px] flex flex-col bg-rose-500 border-rose-500 dark:bg-rose-600 dark:border-rose-600"
            onClick={() => onCardClick?.(data.cards[3]?.id || 'me4')}
          >
            <div className="flex items-center gap-2 mb-2">
              <div className="p-1.5 rounded-lg bg-white/20">
                <CircleDollarSign className="h-4 w-4 text-white" />
              </div>
              <span className="text-sm font-medium text-rose-100">
                총 예상 지출 합계
              </span>
            </div>
            <div className="text-2xl font-bold text-white">
              {formatKoreanAmount(totalAmount)}
            </div>
            <div className="flex items-center gap-1 px-2 py-1 rounded-full text-xs font-semibold mt-auto w-fit bg-white/20 text-white">
              <TrendingUp className="h-3 w-3" />
              {data.cards[3]?.previousLabel || '전월 대비 0.0%'}
            </div>
          </div>
        </div>

        {/* 체크포인트 */}
        {data.checkPoints.length > 0 && (
          <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
            {data.checkPoints.map((cp, idx) => {
              const colorClasses = [
                { bg: 'bg-red-50 dark:bg-red-900/30', border: 'border-red-200 dark:border-red-800', icon: 'text-red-500 dark:text-red-400' },
                { bg: 'bg-amber-50 dark:bg-amber-900/30', border: 'border-amber-200 dark:border-amber-800', icon: 'text-amber-500 dark:text-amber-400' },
                { bg: 'bg-green-50 dark:bg-green-900/30', border: 'border-green-200 dark:border-green-800', icon: 'text-green-500 dark:text-green-400' },
              ];
              const color = colorClasses[idx] || colorClasses[2];

              return (
                <div
                  key={cp.id}
                  className={`p-3 rounded-lg border flex items-start gap-2 ${color.bg} ${color.border}`}
                >
                  {idx === 0 ? (
                    <AlertTriangle className={`h-4 w-4 mt-0.5 shrink-0 ${color.icon}`} />
                  ) : idx === 1 ? (
                    <AlertCircle className={`h-4 w-4 mt-0.5 shrink-0 ${color.icon}`} />
                  ) : (
                    <CheckCircle2 className={`h-4 w-4 mt-0.5 shrink-0 ${color.icon}`} />
                  )}
                  <p className="text-sm text-muted-foreground">{cp.message}</p>
                </div>
              );
            })}
          </div>
        )}
    </CollapsibleDashboardCard>
  );
}
