import { Banknote } from 'lucide-react';
import { formatNumber } from '@/lib/utils/amount';
import type { DetailConfig, FieldDefinition } from '@/components/templates/IntegratedDetailTemplate/types';
import type { WithdrawalRecord } from './types';
import { WITHDRAWAL_TYPE_SELECTOR_OPTIONS } from './types';
import { getVendors, getBankAccounts } from './actions';

// ===== 필드 정의 =====
const fields: FieldDefinition[] = [
  // 출금일
  {
    key: 'withdrawalDate',
    label: '출금일',
    type: 'date',
    placeholder: '출금일을 선택해주세요',
    disabled: (mode) => mode === 'view',
  },
  // 출금계좌
  {
    key: 'bankAccountId',
    label: '출금계좌',
    type: 'select',
    placeholder: '선택',
    fetchOptions: async () => {
      const result = await getBankAccounts();
      if (result.success) {
        return result.data.map((a) => ({
          value: a.id,
          label: a.name,
        }));
      }
      return [];
    },
    disabled: (mode) => mode === 'view',
  },
  // 수취인명
  {
    key: 'recipientName',
    label: '수취인명',
    type: 'text',
    placeholder: '수취인명을 입력해주세요',
    disabled: (mode) => mode === 'view',
  },
  // 출금금액
  {
    key: 'withdrawalAmount',
    label: '출금금액',
    type: 'currency',
    placeholder: '출금금액을 입력해주세요',
    disabled: (mode) => mode === 'view',
  },
  // 적요 (editable)
  {
    key: 'note',
    label: '적요',
    type: 'text',
    placeholder: '적요를 입력해주세요',
    gridSpan: 2,
    disabled: (mode) => mode === 'view',
  },
  // 거래처 (editable, required)
  {
    key: 'vendorId',
    label: '거래처',
    type: 'select',
    required: true,
    placeholder: '선택',
    fetchOptions: async () => {
      const result = await getVendors();
      if (result.success) {
        return result.data.map((v) => ({
          value: v.id,
          label: v.name,
        }));
      }
      return [];
    },
    disabled: (mode) => mode === 'view',
  },
  // 출금 유형 (editable, required)
  {
    key: 'withdrawalType',
    label: '출금 유형',
    type: 'select',
    required: true,
    placeholder: '선택',
    options: WITHDRAWAL_TYPE_SELECTOR_OPTIONS.map((opt) => ({
      value: opt.value,
      label: opt.label,
    })),
    disabled: (mode) => mode === 'view',
  },
];

// ===== Config 정의 =====
export const withdrawalDetailConfig: DetailConfig = {
  title: '출금',
  description: '출금 상세 내역을 등록합니다',
  icon: Banknote,
  basePath: '/accounting/withdrawals',
  fields,
  gridColumns: 2,
  actions: {
    showBack: true,
    showDelete: true,
    showEdit: true,
    backLabel: '목록',
    deleteLabel: '삭제',
    editLabel: '수정',
    deleteConfirmMessage: {
      title: '출금 삭제',
      description: '이 출금 내역을 삭제하시겠습니까? 삭제된 데이터는 복구할 수 없습니다.',
    },
  },
  transformInitialData: (data: Record<string, unknown>): Record<string, unknown> => {
    const record = data as unknown as WithdrawalRecord;
    return {
      withdrawalDate: record.withdrawalDate || '',
      bankAccountId: record.bankAccountId || '',
      recipientName: record.recipientName || '',
      withdrawalAmount: record.withdrawalAmount ? formatNumber(record.withdrawalAmount) : '0',
      note: record.note || '',
      vendorId: record.vendorId || '',
      withdrawalType: record.withdrawalType || 'unset',
    };
  },
  transformSubmitData: (formData: Record<string, unknown>): Partial<WithdrawalRecord> => {
    return {
      withdrawalDate: formData.withdrawalDate as string,
      bankAccountId: formData.bankAccountId as string,
      recipientName: formData.recipientName as string,
      withdrawalAmount: typeof formData.withdrawalAmount === 'string'
        ? parseInt(formData.withdrawalAmount.replace(/,/g, ''), 10)
        : formData.withdrawalAmount as number,
      note: formData.note as string,
      vendorId: formData.vendorId as string,
      withdrawalType: formData.withdrawalType as WithdrawalRecord['withdrawalType'],
    };
  },
};
