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

import type {
  VatApiResponse,
  VatDetailApiResponse,
  EntertainmentApiResponse,
  EntertainmentDetailApiResponse,
  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),
      })),
    })),
  };
}

// ============================================
// 부가세 상세 (VatDetail)
// ============================================

/**
 * VatDetail API 응답 → DetailModalConfig 변환
 * 부가세 상세 모달 설정 생성
 */
export function transformVatDetailResponse(api: VatDetailApiResponse): DetailModalConfig {
  const { period_label, period_options, summary, reference_table, unissued_invoices } = api;

  // 참조 테이블 행 구성: direction(invoice_type) 형식 + 납부세액 행
  const refRows = reference_table.map(row => ({
    category: `${row.direction_label}(${row.invoice_type_label})`,
    supplyAmount: formatNumber(row.supply_amount) + '원',
    taxAmount: formatNumber(row.tax_amount) + '원',
  }));

  // 납부세액 행 추가
  const paymentLabel = summary.is_refund ? '환급세액' : '납부세액';
  refRows.push({
    category: paymentLabel,
    supplyAmount: '',
    taxAmount: formatNumber(summary.estimated_payment) + '원',
  });

  return {
    title: '예상 납부세액',
    periodSelect: {
      enabled: true,
      options: period_options.map(opt => ({ value: opt.value, label: opt.label })),
      defaultValue: period_options[0]?.value,
    },
    summaryCards: [
      { label: '매출 공급가액', value: summary.sales_supply_amount, unit: '원' },
      { label: '매입 공급가액', value: summary.purchases_supply_amount, unit: '원' },
      { label: summary.is_refund ? '예상 환급세액' : '예상 납부세액', value: summary.estimated_payment, unit: '원' },
    ],
    referenceTable: {
      title: `${period_label} 부가세 요약`,
      columns: [
        { key: 'category', label: '구분', align: 'left' },
        { key: 'supplyAmount', label: '공급가액', align: 'right' },
        { key: 'taxAmount', label: '세액', align: 'right' },
      ],
      data: refRows,
    },
    table: {
      title: '세금계산서 미발행/미수취 내역',
      columns: [
        { key: 'no', label: 'No.', align: 'center' },
        { key: 'type', label: '구분', align: 'center' },
        { key: 'issueDate', label: '발생일자', align: 'center', format: 'date' },
        { key: 'vendor', label: '거래처', align: 'left' },
        { key: 'vat', label: '부가세', align: 'right', format: 'currency' },
        { key: 'invoiceStatus', label: '세금계산서 미발행/미수취', align: 'center' },
      ],
      data: unissued_invoices.map((inv, idx) => ({
        no: idx + 1,
        type: inv.direction_label,
        issueDate: inv.issue_date,
        vendor: inv.vendor_name,
        vat: inv.tax_amount,
        invoiceStatus: inv.status,
      })),
      filters: [
        {
          key: 'type',
          options: [
            { value: 'all', label: '전체' },
            { value: '매출', label: '매출' },
            { value: '매입', label: '매입' },
          ],
          defaultValue: 'all',
        },
      ],
      showTotal: true,
      totalLabel: '합계',
      totalValue: unissued_invoices.reduce((sum, inv) => sum + inv.tax_amount, 0),
      totalColumnKey: 'vat',
    },
  };
}

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

/**
 * Entertainment API 응답 → Frontend 타입 변환
 * 접대비 현황 데이터 변환
 */
export function transformEntertainmentResponse(api: EntertainmentApiResponse): EntertainmentData {
  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),
      })),
    })),
  };
}

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

/**
 * Welfare API 응답 → Frontend 타입 변환
 * 복리후생비 현황 데이터 변환
 */
export function transformWelfareResponse(api: WelfareApiResponse): WelfareData {
  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),
      })),
    })),
  };
}

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

/**
 * WelfareDetail API 응답 → DetailModalConfig 변환
 * 복리후생비 상세 모달 설정 생성
 */
// ============================================
// 접대비 상세 (EntertainmentDetail)
// ============================================

/**
 * EntertainmentDetail API 응답 → DetailModalConfig 변환
 * 접대비 상세 모달 설정 생성
 */
export function transformEntertainmentDetailResponse(api: EntertainmentDetailApiResponse): DetailModalConfig {
  const { summary, risk_review, monthly_usage, user_distribution, transactions, calculation, quarterly } = api;

  // 법인 유형 라벨
  const companyTypeLabel = calculation.company_type === 'large' ? '일반법인' : '중소기업';

  return {
    title: '접대비 상세',
    dateFilter: {
      enabled: true,
      defaultPreset: '당월',
      showSearch: true,
    },
    summaryCards: [
      { label: '당해년도 접대비 총 한도', value: summary.annual_limit, unit: '원' },
      { label: '당해년도 접대비 잔여한도', value: summary.annual_remaining, unit: '원' },
      { label: '당해년도 접대비 사용금액', value: summary.annual_used, unit: '원' },
      { label: '당해년도 접대비 초과 금액', value: summary.annual_exceeded, unit: '원' },
    ],
    reviewCards: {
      title: '접대비 검토 필요',
      cards: risk_review.map(r => ({
        label: r.label,
        amount: r.amount,
        subLabel: r.label === '기피업종'
          ? (r.count > 0 ? `불인정 ${r.count}건` : '0건')
          : (r.count > 0 ? `미증빙 ${r.count}건` : '0건'),
      })),
    },
    barChart: {
      title: '월별 접대비 사용 추이',
      data: monthly_usage.map(item => ({
        name: item.label,
        value: item.amount,
      })),
      dataKey: 'value',
      xAxisKey: 'name',
      color: '#60A5FA',
    },
    pieChart: {
      title: '사용자별 접대비 사용 비율',
      data: user_distribution.map(item => ({
        name: item.user_name,
        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: 'useDate', label: '사용일시', align: 'center', format: 'date' },
        { key: 'store', label: '가맹점명', align: 'left' },
        { key: 'amount', label: '사용금액', align: 'right', format: 'currency' },
        { key: 'riskType', label: '리스크', align: 'center' },
      ],
      data: transactions.map((tx, idx) => ({
        no: idx + 1,
        cardName: tx.card_name,
        user: tx.user_name,
        useDate: tx.expense_date,
        store: tx.vendor_name,
        amount: tx.amount,
        riskType: tx.risk_type,
      })),
      filters: [
        {
          key: 'riskType',
          options: [
            { value: 'all', label: '전체' },
            { value: '주말/심야', label: '주말/심야' },
            { value: '기피업종', label: '기피업종' },
            { value: '고액 결제', label: '고액 결제' },
            { value: '증빙 미비', label: '증빙 미비' },
            { value: '정상', label: '정상' },
          ],
          defaultValue: 'all',
        },
      ],
      showTotal: true,
      totalLabel: '합계',
      totalValue: transactions.reduce((sum, tx) => sum + tx.amount, 0),
      totalColumnKey: 'amount',
    },
    referenceTables: [
      {
        title: '접대비 손금한도 계산 - 기본한도',
        columns: [
          { key: 'type', label: '법인 유형', align: 'left' },
          { key: 'annualLimit', label: '연간 기본한도', align: 'right' },
          { key: 'monthlyLimit', label: '월 환산', align: 'right' },
        ],
        data: [
          { type: '일반법인', annualLimit: '12,000,000원', monthlyLimit: '1,000,000원' },
          { type: '중소기업', annualLimit: '36,000,000원', monthlyLimit: '3,000,000원' },
        ],
      },
      {
        title: '수입금액별 추가한도',
        columns: [
          { key: 'range', label: '수입금액 구간', align: 'left' },
          { key: 'formula', label: '추가한도 계산식', align: 'left' },
        ],
        data: [
          { range: '100억원 이하', formula: '수입금액 × 0.2%' },
          { range: '100억 초과 ~ 500억 이하', formula: '2,000만원 + (수입금액 - 100억) × 0.1%' },
          { range: '500억원 초과', formula: '6,000만원 + (수입금액 - 500억) × 0.03%' },
        ],
      },
    ],
    calculationCards: {
      title: '접대비 계산',
      cards: [
        { label: `${companyTypeLabel} 연간 기본한도`, value: calculation.base_limit },
        { label: '당해년도 수입금액별 추가한도', value: calculation.revenue_additional, operator: '+' as const },
        { label: '당해년도 접대비 총 한도', value: calculation.annual_limit, operator: '=' as const },
      ],
    },
    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) || '',
        },
      ],
    },
  };
}

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: '복리후생비 상세',
    dateFilter: {
      enabled: true,
      defaultPreset: '당월',
      showSearch: true,
    },
    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',
        },
      ],
      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) || '',
        },
      ],
    },
  };
}
