/**
 * 거래처(영업) 상세 페이지 설정
 * IntegratedDetailTemplate V2 마이그레이션
 */

import { Building2 } from 'lucide-react';
import type { DetailConfig, FieldDefinition, SectionDefinition } from '@/components/templates/IntegratedDetailTemplate/types';
import type { ClientFormData, Client } from '@/hooks/useClientList';

// ===== 거래처 유형 옵션 =====
const CLIENT_TYPE_OPTIONS = [
  { value: '매입', label: '매입' },
  { value: '매출', label: '매출' },
  { value: '매입매출', label: '매입매출' },
];

// ===== 상태 옵션 =====
const STATUS_OPTIONS = [
  { value: 'true', label: '활성' },
  { value: 'false', label: '비활성' },
];

// ===== 필드 정의 =====
export const clientFields: FieldDefinition[] = [
  // 기본 정보
  {
    key: 'businessNo',
    label: '사업자등록번호',
    type: 'businessNumber',
    required: true,
    placeholder: '000-00-00000',
    validation: [
      { type: 'required', message: '사업자등록번호를 입력해주세요.' },
    ],
  },
  {
    key: 'clientCode',
    label: '거래처 코드',
    type: 'text',
    disabled: true,
    helpText: '자동 생성됩니다',
  },
  {
    key: 'name',
    label: '거래처명',
    type: 'text',
    required: true,
    placeholder: '거래처명 입력',
    validation: [
      { type: 'required', message: '거래처명을 입력해주세요.' },
      { type: 'minLength', value: 2, message: '거래처명은 2자 이상 입력해주세요.' },
    ],
  },
  {
    key: 'representative',
    label: '대표자명',
    type: 'text',
    required: true,
    placeholder: '대표자명 입력',
    validation: [
      { type: 'required', message: '대표자명을 입력해주세요.' },
      { type: 'minLength', value: 2, message: '대표자명은 2자 이상 입력해주세요.' },
    ],
  },
  {
    key: 'clientType',
    label: '거래처 유형',
    type: 'radio',
    required: true,
    options: CLIENT_TYPE_OPTIONS,
  },
  {
    key: 'businessType',
    label: '업태',
    type: 'text',
    placeholder: '제조업, 도소매업 등',
  },
  {
    key: 'businessItem',
    label: '종목',
    type: 'text',
    placeholder: '철강, 건설 등',
  },

  // 연락처 정보
  {
    key: 'address',
    label: '주소',
    type: 'text',
    placeholder: '주소 입력',
    gridSpan: 2,
  },
  {
    key: 'phone',
    label: '전화번호',
    type: 'phone',
    placeholder: '02-1234-5678',
  },
  {
    key: 'mobile',
    label: '모바일',
    type: 'phone',
    placeholder: '010-1234-5678',
  },
  {
    key: 'fax',
    label: '팩스',
    type: 'phone',
    placeholder: '02-1234-5678',
  },
  {
    key: 'email',
    label: '이메일',
    type: 'email',
    placeholder: 'example@company.com',
    validation: [
      {
        type: 'custom',
        message: '올바른 이메일 형식이 아닙니다.',
        validate: (value) => {
          if (!value) return true; // 선택 필드
          return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(value));
        },
      },
    ],
  },

  // 담당자 정보
  {
    key: 'managerName',
    label: '담당자명',
    type: 'text',
    placeholder: '담당자명 입력',
  },
  {
    key: 'managerTel',
    label: '담당자 전화',
    type: 'phone',
    placeholder: '010-1234-5678',
  },
  {
    key: 'systemManager',
    label: '시스템 관리자',
    type: 'text',
    placeholder: '시스템 관리자명',
  },

  // 기타 정보
  {
    key: 'memo',
    label: '메모',
    type: 'textarea',
    placeholder: '메모 입력',
    gridSpan: 2,
  },
  {
    key: 'isActive',
    label: '상태',
    type: 'radio',
    options: STATUS_OPTIONS,
    // Note: default value is handled by formData initialization
  },
];

// ===== 섹션 정의 =====
export const clientSections: SectionDefinition[] = [
  {
    id: 'basicInfo',
    title: '기본 정보',
    description: '거래처의 기본 정보를 입력하세요',
    fields: ['businessNo', 'clientCode', 'name', 'representative', 'clientType', 'businessType', 'businessItem'],
  },
  {
    id: 'contactInfo',
    title: '연락처 정보',
    description: '거래처의 연락처 정보를 입력하세요',
    fields: ['address', 'phone', 'mobile', 'fax', 'email'],
  },
  {
    id: 'managerInfo',
    title: '담당자 정보',
    description: '거래처 담당자 정보를 입력하세요',
    fields: ['managerName', 'managerTel', 'systemManager'],
  },
  {
    id: 'otherInfo',
    title: '기타 정보',
    description: '추가 정보를 입력하세요',
    fields: ['memo', 'isActive'],
  },
];

// ===== 설정 =====
export const clientDetailConfig: DetailConfig<Client> = {
  title: '거래처',
  description: '거래처 정보를 관리합니다',
  icon: Building2,
  basePath: '/ko/sales/client-management-sales-admin',
  fields: clientFields,
  sections: clientSections,
  gridColumns: 2,
  actions: {
    submitLabel: '저장',
    cancelLabel: '취소',
    showDelete: true,
    deleteLabel: '삭제',
    showEdit: true,
    editLabel: '수정',
    showBack: true,
    backLabel: '목록',
    deleteConfirmMessage: {
      title: '거래처 삭제',
      description: '이 거래처를 삭제하시겠습니까? 삭제된 데이터는 복구할 수 없습니다.',
    },
  },
  transformInitialData: (data: Client) => ({
    businessNo: data.businessNo || '',
    clientCode: data.code || '',
    name: data.name || '',
    representative: data.representative || '',
    clientType: data.clientType || '매입',
    businessType: data.businessType || '',
    businessItem: data.businessItem || '',
    address: data.address || '',
    phone: data.phone || '',
    mobile: data.mobile || '',
    fax: data.fax || '',
    email: data.email || '',
    managerName: data.managerName || '',
    managerTel: data.managerTel || '',
    systemManager: data.systemManager || '',
    memo: data.memo || '',
    isActive: data.status === '활성' ? 'true' : 'false',
  }),
  transformSubmitData: (formData): Partial<ClientFormData> => ({
    clientCode: formData.clientCode as string,
    name: formData.name as string,
    businessNo: formData.businessNo as string,
    representative: formData.representative as string,
    clientType: formData.clientType as ClientFormData['clientType'],
    businessType: formData.businessType as string,
    businessItem: formData.businessItem as string,
    address: formData.address as string,
    phone: formData.phone as string,
    mobile: formData.mobile as string,
    fax: formData.fax as string,
    email: formData.email as string,
    managerName: formData.managerName as string,
    managerTel: formData.managerTel as string,
    systemManager: formData.systemManager as string,
    memo: formData.memo as string,
    isActive: formData.isActive === 'true',
    // 기본값 설정
    purchasePaymentDay: '말일',
    salesPaymentDay: '말일',
    taxAgreement: false,
    taxAmount: '',
    taxStartDate: '',
    taxEndDate: '',
    badDebt: false,
    badDebtAmount: '',
    badDebtReceiveDate: '',
    badDebtEndDate: '',
    badDebtProgress: '',
    accountId: '',
    accountPassword: '',
  }),
};
