/**
 * 단가관리 상세 페이지 설정
 * IntegratedDetailTemplate용 config
 */

import { DollarSign } from 'lucide-react';
import type { DetailConfig, FieldDefinition, DetailMode } from '@/components/templates/IntegratedDetailTemplate';
import type { PricingFormData, PricingStatus } from './types';
import { STATUS_OPTIONS, PRICING_STATUS_LABELS } from './types';
import { getVendorList } from './actions';

// 상태 옵션 (all 제외)
const statusFieldOptions = STATUS_OPTIONS
  .filter((o) => o.value !== 'all')
  .map((o) => ({ value: o.value, label: o.label }));

// 필드 정의
const fields: FieldDefinition[] = [
  {
    key: 'pricingNumber',
    label: '단가번호',
    type: 'text',
    disabled: true, // 항상 비활성화 (자동생성)
    placeholder: '자동생성',
  },
  {
    key: 'itemType',
    label: '품목유형',
    type: 'text',
    disabled: true, // 항상 비활성화
  },
  {
    key: 'category',
    label: '카테고리명',
    type: 'text',
    disabled: true,
  },
  {
    key: 'itemName',
    label: '품목명',
    type: 'text',
    disabled: true,
  },
  {
    key: 'spec',
    label: '규격',
    type: 'text',
    disabled: true,
  },
  {
    key: 'orderItemValue',
    label: '무게',
    type: 'text',
    disabled: true,
    helpText: '발주항목 (동적 컬럼)',
  },
  {
    key: 'unit',
    label: '단위',
    type: 'text',
    disabled: true,
  },
  {
    key: 'division',
    label: '구분',
    type: 'text',
    disabled: true,
  },
  {
    key: 'vendor',
    label: '거래처',
    type: 'select',
    disabled: (mode: DetailMode) => mode === 'view',
    fetchOptions: async () => {
      const result = await getVendorList();
      if (result.success && result.data) {
        return result.data.map((v) => ({ value: v.name, label: v.name }));
      }
      return [];
    },
    placeholder: '거래처 선택',
  },
  {
    key: 'sellingPrice',
    label: '판매단가',
    type: 'number',
    disabled: (mode: DetailMode) => mode === 'view',
    placeholder: '판매단가 입력',
    formatValue: (value) => {
      if (value === null || value === undefined || value === '') return '-';
      return Number(value).toLocaleString('ko-KR');
    },
  },
  {
    key: 'status',
    label: '상태',
    type: 'select',
    disabled: (mode: DetailMode) => mode === 'view',
    options: statusFieldOptions,
    placeholder: '상태 선택',
    formatValue: (value) => {
      if (!value) return '-';
      return PRICING_STATUS_LABELS[value as PricingStatus] || String(value);
    },
  },
  {
    key: 'note',
    label: '비고',
    type: 'textarea',
    disabled: (mode: DetailMode) => mode === 'view',
    placeholder: '비고 입력',
    gridSpan: 2,
  },
];

// DetailConfig
export const pricingDetailConfig: DetailConfig = {
  title: '단가',
  description: '단가 정보를 등록하고 관리합니다.',
  icon: DollarSign,
  basePath: '/construction/order/base-info/pricing',
  fields,
  gridColumns: 2,
  actions: {
    showBack: true,
    showDelete: true,
    showEdit: true,
    backLabel: '목록',
    deleteLabel: '삭제',
    editLabel: '수정',
    submitLabel: undefined, // 모드에 따라 자동 결정
    cancelLabel: '취소',
    deleteConfirmMessage: {
      title: '단가 삭제',
      description: '이 단가를 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다.',
    },
  },
  transformInitialData: (data: Record<string, unknown>): Record<string, unknown> => {
    // orderItems에서 첫 번째 항목 추출
    const orderItems = data.orderItems as Array<{ name?: string; value?: string }> | undefined;
    const firstOrderItem = orderItems?.[0];

    return {
      pricingNumber: data.pricingNumber || '자동생성',
      itemType: data.itemType,
      category: data.category,
      itemName: data.itemName,
      spec: data.spec,
      orderItemValue: firstOrderItem?.value || '-',
      unit: data.unit,
      division: data.division,
      vendor: data.vendor,
      sellingPrice: data.sellingPrice,
      status: data.status || 'in_use',
      note: '',
    };
  },
  transformSubmitData: (formData: Record<string, unknown>): Partial<PricingFormData> => ({
    itemType: formData.itemType as string,
    category: formData.category as string,
    itemName: formData.itemName as string,
    spec: formData.spec as string,
    orderItems: [], // 현재는 빈 배열 (기존 값 유지)
    unit: formData.unit as string,
    division: formData.division as string,
    vendor: formData.vendor as string,
    purchasePrice: 0, // 기존 값 유지 필요
    marginRate: 0, // 기존 값 유지 필요
    sellingPrice: Number(formData.sellingPrice) || 0,
    status: formData.status as PricingStatus,
  }),
};

export default pricingDetailConfig;
