/**
 * Dashboard Type2 데이터 변환 함수
 * CEO Dashboard API 데이터 → dashboard_type2 StatCard/TableRow 변환
 */

import type { StatCard, TableRow } from '../mockData';
import type {
  AmountCard,
  DailyReportData,
  ReceivableData,
  DebtCollectionData,
  MonthlyExpenseData,
  CardManagementData,
  EntertainmentData,
  WelfareData,
} from '@/components/business/CEODashboard/types';
import type { TodayIssueData } from '@/hooks/useCEODashboard';
import { formatNumber } from '@/lib/utils/amount';

// ============================================
// 금액 포맷 헬퍼
// ============================================

function formatAmount(amount: number): string {
  const absAmount = Math.abs(amount);
  const sign = amount < 0 ? '-' : '';
  if (absAmount >= 100000000) {
    const value = (absAmount / 100000000).toFixed(1);
    return `${sign}${value}억`;
  } else if (absAmount >= 10000) {
    return `${sign}${formatNumber(Math.round(absAmount / 10000))}만`;
  }
  return `${sign}${formatNumber(absAmount)}원`;
}

function formatAmountWon(amount: number): string {
  const absAmount = Math.abs(amount);
  const sign = amount < 0 ? '-' : '';
  if (absAmount >= 100000000) {
    const value = (absAmount / 100000000).toFixed(1);
    return `${sign}${value}억원`;
  } else if (absAmount >= 10000) {
    return `${sign}${formatNumber(Math.round(absAmount / 10000))}만원`;
  }
  return `${sign}${formatNumber(absAmount)}원`;
}

function formatCurrency(amount: number): string {
  return formatNumber(amount);
}

// ============================================
// AmountCard → StatCard 변환
// ============================================

function cardColorFromId(id: string): StatCard['color'] {
  // 기본 색상 매핑 - ID 패턴 기반
  if (id.includes('cash') || id === 'dr1') return 'blue';
  if (id.includes('income') || id === 'dr3') return 'green';
  if (id.includes('expense') || id === 'dr4' || id.includes('debt')) return 'red';
  if (id.includes('foreign') || id === 'dr2') return 'default';
  return 'default';
}

function amountCardToStatCard(card: AmountCard, colorOverride?: StatCard['color']): StatCard {
  let value: string;
  if (card.currency === 'USD') {
    value = card.amount === 0 ? '$0' : `$${formatCurrency(card.amount)}`;
  } else if (card.unit === '곳' || card.unit === '건') {
    value = `${card.amount}${card.unit}`;
  } else {
    value = card.amount === 0 ? '0원' : formatAmountWon(card.amount);
  }

  return {
    label: card.label,
    value,
    color: colorOverride ?? cardColorFromId(card.id),
    change: card.changeRate,
    changeDirection: card.changeDirection,
  };
}

// ============================================
// 전체요약 탭 변환
// ============================================

export function transformOverviewStats(dailyReport: DailyReportData | null): StatCard[] {
  if (!dailyReport) return [];
  return dailyReport.cards.map((card) => {
    let color: StatCard['color'] = 'default';
    if (card.id === 'dr1') color = 'blue';
    else if (card.id === 'dr3') color = 'green';
    else if (card.id === 'dr4') color = 'orange';
    return amountCardToStatCard(card, color);
  });
}

export function transformOverviewRecentOrders(
  receivable: ReceivableData | null,
): TableRow[] {
  if (!receivable) return [];
  // 미수금 체크포인트에서 간단한 요약 테이블 생성
  // 실제로는 API에서 최근 수주 데이터를 가져와야 하지만,
  // 현재 API 구조상 미수금 카드 데이터로 요약 생성
  return receivable.cards.map((card, idx) => ({
    no: idx + 1,
    항목: card.label,
    금액: card.amount === 0 ? '0원' : formatAmountWon(card.amount),
    비고: card.subLabel ?? '-',
  }));
}

// ============================================
// 영업/매출 탭 변환
// ============================================

export function transformSalesStats(
  receivable: ReceivableData | null,
  debtCollection: DebtCollectionData | null,
): StatCard[] {
  const stats: StatCard[] = [];

  if (receivable) {
    // 누적 미수금
    const cumulative = receivable.cards.find((c) => c.id === 'rv1');
    if (cumulative) {
      stats.push({
        label: cumulative.label,
        value: formatAmount(cumulative.amount),
        color: 'red',
      });
    }
    // 당월 미수금
    const monthly = receivable.cards.find((c) => c.id === 'rv2');
    if (monthly) {
      stats.push({
        label: monthly.label,
        value: formatAmount(monthly.amount),
        color: 'orange',
      });
    }
    // 거래처 현황
    const vendors = receivable.cards.find((c) => c.id === 'rv3');
    if (vendors) {
      stats.push({
        label: vendors.label,
        value: `${vendors.amount}${vendors.unit ?? '곳'}`,
        color: 'blue',
      });
    }
  }

  if (debtCollection) {
    const collecting = debtCollection.cards.find((c) => c.id === 'dc2');
    if (collecting) {
      stats.push({
        label: '채권추심 중',
        value: formatAmount(collecting.amount),
        color: 'red',
      });
    }
  }

  return stats;
}

export function transformReceivableTable(receivable: ReceivableData | null): TableRow[] {
  if (!receivable) return [];
  // 체크포인트에서 미수금 정보 추출하여 테이블 구성
  // 실제 미수금 상세 데이터가 없으므로 카드 데이터에서 생성
  const rows: TableRow[] = [];
  receivable.cards.forEach((card, idx) => {
    if (card.subItems) {
      card.subItems.forEach((sub) => {
        rows.push({
          no: rows.length + 1,
          항목: `${card.label} - ${sub.label}`,
          금액: typeof sub.value === 'number' ? formatCurrency(sub.value) : String(sub.value),
        });
      });
    } else {
      rows.push({
        no: idx + 1,
        항목: card.label,
        금액: formatCurrency(card.amount),
      });
    }
  });
  return rows;
}

export function transformDebtTable(debtCollection: DebtCollectionData | null): TableRow[] {
  if (!debtCollection) return [];
  return debtCollection.cards.map((card, idx) => ({
    no: idx + 1,
    항목: card.label,
    금액: formatAmountWon(card.amount),
    비고: card.subLabel ?? '-',
  }));
}

// ============================================
// 재무관리 탭 변환
// ============================================

export function transformFinanceStats(dailyReport: DailyReportData | null): StatCard[] {
  if (!dailyReport) return [];
  return dailyReport.cards.map((card) => {
    let color: StatCard['color'] = 'default';
    if (card.id === 'dr1') color = card.amount < 0 ? 'red' : 'blue';
    else if (card.id === 'dr3') color = 'green';
    return amountCardToStatCard(card, color);
  });
}

export function transformExpenseTable(monthlyExpense: MonthlyExpenseData | null): TableRow[] {
  if (!monthlyExpense) return [];
  return monthlyExpense.cards.map((card, idx) => ({
    no: idx + 1,
    항목: card.label,
    금액: card.amount === 0 ? '0원' : formatAmountWon(card.amount),
    전월대비: card.previousLabel ?? '-',
    비율: '-',
  }));
}

export function transformCardTable(cardManagement: CardManagementData | null): TableRow[] {
  if (!cardManagement) return [];
  return cardManagement.cards.map((card, idx) => ({
    no: idx + 1,
    항목: card.label,
    금액: card.amount === 0 ? '0원' : formatAmountWon(card.amount),
    비고: card.previousLabel ?? card.subLabel ?? '-',
  }));
}

// ============================================
// 경비관리 탭 변환
// ============================================

export function transformExpenseManagementStats(
  entertainment: EntertainmentData | null,
  welfare: WelfareData | null,
): StatCard[] {
  const stats: StatCard[] = [];

  if (entertainment) {
    const used = entertainment.cards.find((c) => c.id === 'et_used');
    const remaining = entertainment.cards.find((c) => c.id === 'et_remaining');
    if (used) {
      stats.push({
        label: '접대비 사용',
        value: formatAmountWon(used.amount),
        color: 'blue',
      });
    }
    if (remaining) {
      stats.push({
        label: '접대비 잔여한도',
        value: formatAmountWon(remaining.amount),
        color: 'green',
      });
    }
  }

  if (welfare) {
    const used = welfare.cards.find((c) => c.id === 'wf_used');
    const remaining = welfare.cards.find((c) => c.id === 'wf_remaining');
    if (used) {
      stats.push({
        label: '복리후생비 사용',
        value: used.amount === 0 ? '0원' : formatAmountWon(used.amount),
        color: 'default',
      });
    }
    if (remaining) {
      stats.push({
        label: '복리후생비 잔여한도',
        value: formatAmountWon(remaining.amount),
        color: 'green',
      });
    }
  }

  return stats;
}

export function transformEntertainmentTable(entertainment: EntertainmentData | null): TableRow[] {
  if (!entertainment) return [];
  return entertainment.cards.map((card, idx) => ({
    no: idx + 1,
    항목: card.label,
    금액: card.amount === 0 ? '0원' : formatAmountWon(card.amount),
    비고: card.subLabel ?? '-',
  }));
}

export function transformWelfareTable(welfare: WelfareData | null): TableRow[] {
  if (!welfare) return [];
  return welfare.cards.map((card, idx) => ({
    no: idx + 1,
    항목: card.label,
    금액: card.amount === 0 ? '0원' : formatAmountWon(card.amount),
    비고: card.subLabel ?? '-',
  }));
}

// ============================================
// 일정/이슈 탭 변환
// ============================================

export function transformScheduleStats(
  todayIssue: TodayIssueData | null,
): StatCard[] {
  if (!todayIssue) return [];
  return [
    {
      label: '오늘 이슈',
      value: `${todayIssue.totalCount}건`,
      color: 'blue' as const,
    },
    {
      label: '미처리 건수',
      value: `${todayIssue.items.filter((i) => i.needsApproval).length}건`,
      color: 'red' as const,
    },
  ];
}

// ============================================
// 롤링 텍스트용 변환
// ============================================

export function statsToRollingItems(stats: StatCard[]) {
  return stats.map((s) => ({
    label: s.label,
    value: s.value,
    color: (s.color ?? 'default') as 'default' | 'green' | 'blue' | 'red' | 'orange',
  }));
}

// ============================================
// 차트 데이터 변환
// ============================================

export interface ExpenseChartItem {
  name: string;
  value: number;
  color: string;
}

export function transformExpenseChartData(monthlyExpense: MonthlyExpenseData | null): ExpenseChartItem[] {
  if (!monthlyExpense) return [];
  const colorMap: Record<string, string> = {
    매입: '#3b82f6',
    카드: '#f97316',
    발행어음: '#8b5cf6',
    '총 예상 지출 합계': '#94a3b8',
    인건비: '#10b981',
    운영비: '#8b5cf6',
    기타: '#94a3b8',
  };
  return monthlyExpense.cards
    .filter((card) => card.id !== 'me4') // 합계 제외
    .filter((card) => Number(card.amount) > 0) // 0원 제외
    .map((card) => ({
      name: card.label,
      value: Number(card.amount),
      color: colorMap[card.label] ?? '#94a3b8',
    }));
}

export interface ReceivableChartItem {
  name: string;
  매출액: number;
  미수금: number;
}

export function transformReceivableChartData(receivable: ReceivableData | null): ReceivableChartItem[] {
  if (!receivable) return [];
  // 카드별 데이터에서 매출/미수금 비교 차트 생성
  const rv1 = receivable.cards.find((c) => c.id === 'rv1');
  const rv2 = receivable.cards.find((c) => c.id === 'rv2');

  if (!rv1?.subItems || !rv2?.subItems) return [];

  const sales = rv1.subItems.find((s) => s.label === '매출');
  const deposits = rv1.subItems.find((s) => s.label === '입금');

  if (!sales || !deposits) return [];

  return [
    {
      name: '매출',
      매출액: Number(sales.value) || 0,
      미수금: 0,
    },
    {
      name: '입금',
      매출액: Number(deposits.value) || 0,
      미수금: 0,
    },
    {
      name: '미수금',
      매출액: 0,
      미수금: Number(rv2.amount),
    },
  ];
}

export interface OverviewChartItem {
  name: string;
  금액: number;
  color: string;
}

export function transformOverviewChartData(dailyReport: DailyReportData | null): OverviewChartItem[] {
  if (!dailyReport) return [];
  const colorMap: Record<string, string> = {
    dr1: '#3b82f6', // 현금성 자산 - blue
    dr2: '#8b5cf6', // 외국환 - purple
    dr3: '#10b981', // 입금 - green
    dr4: '#f97316', // 출금 - orange
  };
  return dailyReport.cards.map((card) => ({
    name: card.label.replace(' 합계', ''),
    금액: Math.abs(Number(card.amount)),
    color: colorMap[card.id] ?? '#94a3b8',
  }));
}
