/**
 * 부가세 (Vat) + 접대비 (Entertainment) + 복리후생비 (Welfare) 변환
 */

import type {
  VatApiResponse,
  EntertainmentApiResponse,
  WelfareApiResponse,
  WelfareDetailApiResponse,
} from '../types';
import type {
  VatData,
  EntertainmentData,
  WelfareData,
  CheckPointType,
  DetailModalConfig,
} from '@/components/business/CEODashboard/types';
import { validateHighlightColor } from './common';
import { formatNumber } from '@/lib/utils/amount';

// ============================================
// 부가세 (Vat)
// ============================================

/**
 * Vat API 응답 → Frontend 타입 변환
 * 부가세 현황 데이터 변환
 */
export function transformVatResponse(api: VatApiResponse): VatData {
  return {
    cards: api.cards.map((card) => ({
      id: card.id,
      label: card.label,
      amount: card.amount,
      subLabel: card.subLabel,
      unit: card.unit,
    })),
    checkPoints: api.check_points.map((cp) => ({
      id: cp.id,
      type: cp.type as CheckPointType,
      message: cp.message,
      highlights: cp.highlights?.map((h) => ({
        text: h.text,
        color: validateHighlightColor(h.color),
      })),
    })),
  };
}

// ============================================
// 접대비 (Entertainment)
// ============================================

/**
 * Entertainment API 응답 → Frontend 타입 변환
 * 접대비 현황 데이터 변환
 */
export function transformEntertainmentResponse(api: EntertainmentApiResponse): EntertainmentData {
  // 사용금액(et_used)을 잔여한도(et_remaining) 앞으로 재배치
  const reordered = [...api.cards];
  const usedIdx = reordered.findIndex((c) => c.id === 'et_used');
  const remainIdx = reordered.findIndex((c) => c.id === 'et_remaining');
  if (usedIdx > remainIdx && remainIdx >= 0) {
    const [used] = reordered.splice(usedIdx, 1);
    reordered.splice(remainIdx, 0, used);
  }

  return {
    cards: reordered.map((card) => ({
      id: card.id,
      label: card.label,
      amount: card.amount,
      subLabel: card.subLabel,
      unit: card.unit,
    })),
    checkPoints: api.check_points.map((cp) => ({
      id: cp.id,
      type: cp.type as CheckPointType,
      message: cp.message,
      highlights: cp.highlights?.map((h) => ({
        text: h.text,
        color: validateHighlightColor(h.color),
      })),
    })),
  };
}

// ============================================
// 복리후생비 (Welfare)
// ============================================

/**
 * Welfare API 응답 → Frontend 타입 변환
 * 복리후생비 현황 데이터 변환
 */
export function transformWelfareResponse(api: WelfareApiResponse): WelfareData {
  // 사용금액(wf_used)을 잔여한도(wf_remaining) 앞으로 재배치
  const reordered = [...api.cards];
  const usedIdx = reordered.findIndex((c) => c.id === 'wf_used');
  const remainIdx = reordered.findIndex((c) => c.id === 'wf_remaining');
  if (usedIdx > remainIdx && remainIdx >= 0) {
    const [used] = reordered.splice(usedIdx, 1);
    reordered.splice(remainIdx, 0, used);
  }

  return {
    cards: reordered.map((card) => ({
      id: card.id,
      label: card.label,
      amount: card.amount,
      subLabel: card.subLabel,
      unit: card.unit,
    })),
    checkPoints: api.check_points.map((cp) => ({
      id: cp.id,
      type: cp.type as CheckPointType,
      message: cp.message,
      highlights: cp.highlights?.map((h) => ({
        text: h.text,
        color: validateHighlightColor(h.color),
      })),
    })),
  };
}

// ============================================
// 복리후생비 상세 (WelfareDetail)
// ============================================

/**
 * WelfareDetail API 응답 → DetailModalConfig 변환
 * 복리후생비 상세 모달 설정 생성
 */
export function transformWelfareDetailResponse(api: WelfareDetailApiResponse): DetailModalConfig {
  const { summary, monthly_usage, category_distribution, transactions, calculation, quarterly } = api;

  // 계산 방식에 따른 calculationCards 생성
  const calculationCards = calculation.type === 'fixed'
    ? {
        title: '복리후생비 계산',
        subtitle: `직원당 정액 금액/월 ${formatNumber(calculation.fixed_amount_per_month ?? 200000)}원`,
        cards: [
          { label: '직원 수', value: calculation.employee_count, unit: '명' },
          { label: '연간 직원당 월급 금액', value: calculation.annual_amount_per_employee ?? 0, unit: '원', operator: '×' as const },
          { label: '당해년도 복리후생비 총 한도', value: calculation.annual_limit, unit: '원', operator: '=' as const },
        ],
      }
    : {
        title: '복리후생비 계산',
        subtitle: `연봉 총액 기준 비율 ${((calculation.ratio ?? 0.05) * 100).toFixed(1)}%`,
        cards: [
          { label: '연봉 총액', value: calculation.total_salary ?? 0, unit: '원' },
          { label: '비율', value: (calculation.ratio ?? 0.05) * 100, unit: '%', operator: '×' as const },
          { label: '당해년도 복리후생비 총 한도', value: calculation.annual_limit, unit: '원', operator: '=' as const },
        ],
      };

  // 분기 라벨 가져오기 (현재 분기 기준)
  const currentQuarter = quarterly.find(q => q.used !== null)?.quarter ?? 1;
  const quarterLabel = `${currentQuarter}사분기`;

  return {
    title: '복리후생비 상세',
    summaryCards: [
      // 1행: 당해년도 기준
      { label: '당해년도 복리후생비 계정', value: summary.annual_account, unit: '원' },
      { label: '당해년도 복리후생비 한도', value: summary.annual_limit, unit: '원' },
      { label: '당해년도 복리후생비 사용', value: summary.annual_used, unit: '원' },
      { label: '당해년도 잔여한도', value: summary.annual_remaining, unit: '원' },
      // 2행: 분기 기준
      { label: `${quarterLabel} 복리후생비 총 한도`, value: summary.quarterly_limit, unit: '원' },
      { label: `${quarterLabel} 복리후생비 잔여한도`, value: summary.quarterly_remaining, unit: '원' },
      { label: `${quarterLabel} 복리후생비 사용금액`, value: summary.quarterly_used, unit: '원' },
      { label: `${quarterLabel} 복리후생비 초과 금액`, value: summary.quarterly_exceeded, unit: '원' },
    ],
    barChart: {
      title: '월별 복리후생비 사용 추이',
      data: monthly_usage.map(item => ({
        name: item.label,
        value: item.amount,
      })),
      dataKey: 'value',
      xAxisKey: 'name',
      color: '#60A5FA',
    },
    pieChart: {
      title: '항목별 사용 비율',
      data: category_distribution.map(item => ({
        name: item.category_label,
        value: item.amount,
        percentage: item.percentage,
        color: item.color,
      })),
    },
    table: {
      title: '일별 복리후생비 사용 내역',
      columns: [
        { key: 'no', label: 'No.', align: 'center' },
        { key: 'cardName', label: '카드명', align: 'left' },
        { key: 'user', label: '사용자', align: 'center' },
        { key: 'date', label: '사용일자', align: 'center', format: 'date' },
        { key: 'store', label: '가맹점명', align: 'left' },
        { key: 'amount', label: '사용금액', align: 'right', format: 'currency' },
        { key: 'usageType', label: '사용항목', align: 'center' },
      ],
      data: transactions.map((tx, idx) => ({
        no: idx + 1,
        cardName: tx.card_name,
        user: tx.user_name,
        date: tx.transaction_date,
        store: tx.merchant_name,
        amount: tx.amount,
        usageType: tx.usage_type_label,
      })),
      filters: [
        {
          key: 'usageType',
          options: [
            { value: 'all', label: '전체' },
            { value: '식비', label: '식비' },
            { value: '건강검진', label: '건강검진' },
            { value: '경조사비', label: '경조사비' },
            { value: '기타', label: '기타' },
          ],
          defaultValue: 'all',
        },
        {
          key: 'sortOrder',
          options: [
            { value: 'latest', label: '최신순' },
            { value: 'oldest', label: '등록순' },
            { value: 'amountDesc', label: '금액 높은순' },
            { value: 'amountAsc', label: '금액 낮은순' },
          ],
          defaultValue: 'latest',
        },
      ],
      showTotal: true,
      totalLabel: '합계',
      totalValue: transactions.reduce((sum, tx) => sum + tx.amount, 0),
      totalColumnKey: 'amount',
    },
    calculationCards,
    quarterlyTable: {
      title: '복리후생비 현황',
      rows: [
        {
          label: '한도금액',
          q1: quarterly[0]?.limit ?? 0,
          q2: quarterly[1]?.limit ?? 0,
          q3: quarterly[2]?.limit ?? 0,
          q4: quarterly[3]?.limit ?? 0,
          total: quarterly.reduce((sum, q) => sum + (q.limit ?? 0), 0),
        },
        {
          label: '이월금액',
          q1: quarterly[0]?.carryover ?? 0,
          q2: quarterly[1]?.carryover ?? '',
          q3: quarterly[2]?.carryover ?? '',
          q4: quarterly[3]?.carryover ?? '',
          total: '',
        },
        {
          label: '사용금액',
          q1: quarterly[0]?.used ?? '',
          q2: quarterly[1]?.used ?? '',
          q3: quarterly[2]?.used ?? '',
          q4: quarterly[3]?.used ?? '',
          total: quarterly.reduce((sum, q) => sum + (q.used ?? 0), 0) || '',
        },
        {
          label: '잔여한도',
          q1: quarterly[0]?.remaining ?? '',
          q2: quarterly[1]?.remaining ?? '',
          q3: quarterly[2]?.remaining ?? '',
          q4: quarterly[3]?.remaining ?? '',
          total: '',
        },
        {
          label: '초과금액',
          q1: quarterly[0]?.exceeded ?? '',
          q2: quarterly[1]?.exceeded ?? '',
          q3: quarterly[2]?.exceeded ?? '',
          q4: quarterly[3]?.exceeded ?? '',
          total: quarterly.reduce((sum, q) => sum + (q.exceeded ?? 0), 0) || '',
        },
      ],
    },
  };
}
