// ===== 어음 구분 =====
export type BillType = 'received' | 'issued';

export const BILL_TYPE_LABELS: Record<BillType, string> = {
  received: '수취',
  issued: '발행',
};

export const BILL_TYPE_OPTIONS = [
  { value: 'received', label: '수취' },
  { value: 'issued', label: '발행' },
];

export const BILL_TYPE_FILTER_OPTIONS = [
  { value: 'all', label: '전체' },
  { value: 'received', label: '수취' },
  { value: 'issued', label: '발행' },
];

// ===== 어음 상태 (수취) =====
export type ReceivedBillStatus =
  | 'stored'           // 보관중
  | 'maturityAlert'    // 만기입금(7일전)
  | 'maturityResult'   // 만기결과
  | 'paymentComplete'  // 결제완료
  | 'dishonored';      // 부도

export const RECEIVED_BILL_STATUS_LABELS: Record<ReceivedBillStatus, string> = {
  stored: '보관중',
  maturityAlert: '만기입금(7일전)',
  maturityResult: '만기결과',
  paymentComplete: '결제완료',
  dishonored: '부도',
};

export const RECEIVED_BILL_STATUS_OPTIONS = [
  { value: 'stored', label: '보관중' },
  { value: 'maturityAlert', label: '만기입금(7일전)' },
  { value: 'maturityResult', label: '만기결과' },
  { value: 'paymentComplete', label: '결제완료' },
  { value: 'dishonored', label: '부도' },
];

// ===== 어음 상태 (발행) =====
export type IssuedBillStatus =
  | 'stored'              // 보관중
  | 'maturityAlert'       // 만기입금(7일전)
  | 'collectionRequest'   // 추심의뢰
  | 'collectionComplete'  // 추심완료
  | 'suing'               // 추소중
  | 'dishonored';         // 부도

export const ISSUED_BILL_STATUS_LABELS: Record<IssuedBillStatus, string> = {
  stored: '보관중',
  maturityAlert: '만기입금(7일전)',
  collectionRequest: '추심의뢰',
  collectionComplete: '추심완료',
  suing: '추소중',
  dishonored: '부도',
};

export const ISSUED_BILL_STATUS_OPTIONS = [
  { value: 'stored', label: '보관중' },
  { value: 'maturityAlert', label: '만기입금(7일전)' },
  { value: 'collectionRequest', label: '추심의뢰' },
  { value: 'collectionComplete', label: '추심완료' },
  { value: 'suing', label: '추소중' },
  { value: 'dishonored', label: '부도' },
];

// ===== 통합 상태 타입 =====
export type BillStatus = ReceivedBillStatus | IssuedBillStatus;

export const BILL_STATUS_COLORS: Record<BillStatus, string> = {
  stored: 'bg-blue-100 text-blue-800',
  maturityAlert: 'bg-yellow-100 text-yellow-800',
  maturityResult: 'bg-orange-100 text-orange-800',
  paymentComplete: 'bg-green-100 text-green-800',
  collectionRequest: 'bg-purple-100 text-purple-800',
  collectionComplete: 'bg-teal-100 text-teal-800',
  suing: 'bg-red-100 text-red-800',
  dishonored: 'bg-gray-100 text-gray-800',
};

// ===== 헤더 탭 옵션 (스크린샷 기준) =====
export const HEADER_TAB_OPTIONS = [
  { value: 'daily', label: '일마감조' },
  { value: 'yesterday', label: '전일' },
  { value: 'today', label: '금일' },
  { value: 'unsettled', label: '미결' },
  { value: 'bill', label: '어음' },
];

// ===== 상태 필터 옵션 (보관중 셀렉트박스) =====
export const BILL_STATUS_FILTER_OPTIONS = [
  { value: 'all', label: '전체' },
  { value: 'stored', label: '보관중' },
  { value: 'transfer', label: '전매' },
  { value: 'guarantee', label: '보증' },
  { value: 'maturity', label: '만기입금/결제' },
  { value: 'etc', label: '기타' },
];

// ===== 전자 필터 옵션 =====
export const ELECTRONIC_FILTER_OPTIONS = [
  { value: 'all', label: '전체' },
  { value: 'electronic', label: '전자' },
  { value: 'paper', label: '지류' },
];

// ===== 정렬 옵션 =====
export type SortOption = 'latest' | 'oldest' | 'amountHigh' | 'amountLow' | 'maturityDate';

export const SORT_OPTIONS = [
  { value: 'latest', label: '최신순' },
  { value: 'oldest', label: '등록순' },
  { value: 'amountHigh', label: '금액 높은순' },
  { value: 'amountLow', label: '금액 낮은순' },
  { value: 'maturityDate', label: '만기일순' },
];

// ===== 차수 레코드 =====
export interface InstallmentRecord {
  id: string;
  date: string;       // 일자
  amount: number;     // 금액
  note: string;       // 비고
}

// ===== 어음 레코드 =====
export interface BillRecord {
  id: string;
  billNumber: string;        // 어음번호
  billType: BillType;        // 구분 (수취/발행)
  vendorId: string;          // 거래처 ID
  vendorName: string;        // 거래처명
  amount: number;            // 금액
  issueDate: string;         // 발행일
  maturityDate: string;      // 만기일
  status: BillStatus;        // 상태
  reason: string;            // 이유
  installmentCount: number;  // 추수(차수)
  note: string;              // 메모/비고
  installments: InstallmentRecord[];  // 차수 관리 내역
  createdAt: string;
  updatedAt: string;
}

// ===== 거래처 타입 =====
export interface Vendor {
  id: string;
  name: string;
  email?: string;
  phone?: string;
}

// ===== 상태 라벨 헬퍼 함수 =====
export function getBillStatusLabel(billType: BillType, status: BillStatus): string {
  if (billType === 'received') {
    return RECEIVED_BILL_STATUS_LABELS[status as ReceivedBillStatus] || status;
  }
  return ISSUED_BILL_STATUS_LABELS[status as IssuedBillStatus] || status;
}

// ===== 상태 옵션 헬퍼 함수 =====
export function getBillStatusOptions(billType: BillType) {
  if (billType === 'received') {
    return RECEIVED_BILL_STATUS_OPTIONS;
  }
  return ISSUED_BILL_STATUS_OPTIONS;
}

// ===== API 응답 타입 =====
export interface BillApiInstallment {
  id: number;
  bill_id: number;
  type?: string;
  installment_date: string;
  amount: string;
  counterparty?: string | null;
  note: string | null;
  created_at: string;
  updated_at: string;
}

export interface BillApiData {
  id: number;
  tenant_id: number;
  bill_number: string;
  bill_type: BillType;
  client_id: number | null;
  client_name: string | null;
  amount: string;
  issue_date: string;
  maturity_date: string | null;
  status: BillStatus;
  reason: string | null;
  installment_count: number;
  note: string | null;
  is_electronic: boolean;
  bank_account_id: number | null;
  created_by: number | null;
  updated_by: number | null;
  created_at: string;
  updated_at: string;
  client?: {
    id: number;
    name: string;
  } | null;
  bank_account?: {
    id: number;
    bank_name: string;
    account_name: string;
  } | null;
  installments?: BillApiInstallment[];
  // V8 확장 필드
  instrument_type?: string;
  medium?: string;
  bill_category?: string;
  electronic_bill_no?: string | null;
  registration_org?: string | null;
  drawee?: string | null;
  acceptance_status?: string | null;
  acceptance_date?: string | null;
  acceptance_refusal_date?: string | null;
  acceptance_refusal_reason?: string | null;
  endorsement?: string | null;
  endorsement_order?: string | null;
  storage_place?: string | null;
  issuer_bank?: string | null;
  is_discounted?: boolean;
  discount_date?: string | null;
  discount_bank?: string | null;
  discount_rate?: string | null;
  discount_amount?: string | null;
  endorsement_date?: string | null;
  endorsee?: string | null;
  endorsement_reason?: string | null;
  collection_bank?: string | null;
  collection_request_date?: string | null;
  collection_fee?: string | null;
  collection_complete_date?: string | null;
  collection_result?: string | null;
  collection_deposit_date?: string | null;
  collection_deposit_amount?: string | null;
  settlement_bank?: string | null;
  payment_method?: string | null;
  actual_payment_date?: string | null;
  payment_place?: string | null;
  payment_place_detail?: string | null;
  renewal_date?: string | null;
  renewal_new_bill_no?: string | null;
  renewal_reason?: string | null;
  recourse_date?: string | null;
  recourse_amount?: string | null;
  recourse_target?: string | null;
  recourse_reason?: string | null;
  buyback_date?: string | null;
  buyback_amount?: string | null;
  buyback_bank?: string | null;
  dishonored_date?: string | null;
  dishonored_reason?: string | null;
  has_protest?: boolean;
  protest_date?: string | null;
  recourse_notice_date?: string | null;
  recourse_notice_deadline?: string | null;
  is_split?: boolean;
}

export interface BillApiResponse {
  success: boolean;
  message: string;
  data: BillApiData | BillApiData[] | {
    data: BillApiData[];
    current_page: number;
    last_page: number;
    per_page: number;
    total: number;
  };
}

// ===== API → Frontend 변환 함수 =====
export function transformApiToFrontend(apiData: BillApiData): BillRecord {
  return {
    id: String(apiData.id),
    billNumber: apiData.bill_number,
    billType: apiData.bill_type,
    vendorId: apiData.client_id ? String(apiData.client_id) : '',
    vendorName: apiData.client?.name || apiData.client_name || '',
    amount: parseFloat(apiData.amount),
    issueDate: apiData.issue_date,
    maturityDate: apiData.maturity_date || '',
    status: apiData.status,
    reason: apiData.reason || '',
    installmentCount: apiData.installment_count,
    note: apiData.note || '',
    installments: (apiData.installments || []).map((inst) => ({
      id: String(inst.id),
      date: inst.installment_date,
      amount: parseFloat(inst.amount),
      note: inst.note || '',
    })),
    createdAt: apiData.created_at,
    updatedAt: apiData.updated_at,
  };
}

// ===== Frontend → API 변환 함수 (V8 전체 필드 전송) =====
export function transformFrontendToApi(data: Partial<BillRecord>): Record<string, unknown> {
  const result: Record<string, unknown> = {};

  if (data.billNumber !== undefined) result.bill_number = data.billNumber;
  if (data.billType !== undefined) result.bill_type = data.billType;
  if (data.vendorId !== undefined) result.client_id = data.vendorId ? parseInt(data.vendorId) : null;
  if (data.vendorName !== undefined) result.client_name = data.vendorName || null;
  if (data.amount !== undefined) result.amount = data.amount;
  if (data.issueDate !== undefined) result.issue_date = data.issueDate;
  if (data.maturityDate !== undefined) result.maturity_date = data.maturityDate || null;
  if (data.status !== undefined) result.status = data.status;
  if (data.reason !== undefined) result.reason = data.reason || null;
  if (data.note !== undefined) result.note = data.note || null;

  if (data.installments !== undefined) {
    result.installments = data.installments.map((inst) => ({
      date: inst.date,
      amount: inst.amount,
      note: inst.note || null,
    }));
  }

  return result;
}

// ===== BillFormData → API payload 변환 (V8 전체 필드 전송) =====
export function transformFormDataToApi(data: BillFormData, vendorName: string): Record<string, unknown> {
  const isReceived = data.direction === 'received';
  const orNull = (v: string) => v || null;
  const orNullNum = (v: number) => v || null;
  const orNullDate = (v: string) => v || null;

  return {
    // 기존 12개 필드
    bill_number: data.billNumber,
    bill_type: data.direction,
    client_id: isReceived ? (data.vendor ? parseInt(data.vendor) : null) : (data.payee ? parseInt(data.payee) : null),
    client_name: vendorName || null,
    amount: data.amount,
    issue_date: data.issueDate,
    maturity_date: orNullDate(data.maturityDate),
    status: isReceived ? data.receivedStatus : data.issuedStatus,
    note: orNull(data.note),
    is_electronic: data.medium === 'electronic',
    // V8 확장 필드
    instrument_type: data.instrumentType,
    medium: data.medium,
    bill_category: orNull(data.billCategory),
    electronic_bill_no: orNull(data.electronicBillNo),
    registration_org: orNull(data.registrationOrg),
    drawee: orNull(data.drawee),
    acceptance_status: orNull(data.acceptanceStatus),
    acceptance_date: orNullDate(data.acceptanceDate),
    acceptance_refusal_date: orNullDate(data.acceptanceRefusalDate),
    acceptance_refusal_reason: orNull(data.acceptanceRefusalReason),
    endorsement: orNull(data.endorsement),
    endorsement_order: orNull(data.endorsementOrder),
    storage_place: orNull(data.storagePlace),
    issuer_bank: orNull(data.issuerBank),
    is_discounted: data.isDiscounted,
    discount_date: orNullDate(data.discountDate),
    discount_bank: orNull(data.discountBank),
    discount_rate: orNullNum(data.discountRate),
    discount_amount: orNullNum(data.discountAmount),
    endorsement_date: orNullDate(data.endorsementDate),
    endorsee: orNull(data.endorsee),
    endorsement_reason: orNull(data.endorsementReason),
    collection_bank: orNull(data.collectionBank),
    collection_request_date: orNullDate(data.collectionRequestDate),
    collection_fee: orNullNum(data.collectionFee),
    collection_complete_date: orNullDate(data.collectionCompleteDate),
    collection_result: orNull(data.collectionResult),
    collection_deposit_date: orNullDate(data.collectionDepositDate),
    collection_deposit_amount: orNullNum(data.collectionDepositAmount),
    settlement_bank: orNull(data.settlementBank),
    payment_method: orNull(data.paymentMethod),
    actual_payment_date: orNullDate(data.actualPaymentDate),
    payment_place: orNull(data.paymentPlace),
    payment_place_detail: orNull(data.paymentPlaceDetail),
    renewal_date: orNullDate(data.renewalDate),
    renewal_new_bill_no: orNull(data.renewalNewBillNo),
    renewal_reason: orNull(data.renewalReason),
    recourse_date: orNullDate(data.recourseDate),
    recourse_amount: orNullNum(data.recourseAmount),
    recourse_target: orNull(data.recourseTarget),
    recourse_reason: orNull(data.recourseReason),
    buyback_date: orNullDate(data.buybackDate),
    buyback_amount: orNullNum(data.buybackAmount),
    buyback_bank: orNull(data.buybackBank),
    dishonored_date: orNullDate(data.dishonoredDate),
    dishonored_reason: orNull(data.dishonoredReason),
    has_protest: data.hasProtest,
    protest_date: orNullDate(data.protestDate),
    recourse_notice_date: orNullDate(data.recourseNoticeDate),
    recourse_notice_deadline: orNullDate(data.recourseNoticeDeadline),
    is_split: data.isSplit,
    // 이력(차수)
    installments: data.installments.map(inst => ({
      date: inst.date,
      type: inst.type || 'other',
      amount: inst.amount,
      counterparty: orNull(inst.counterparty),
      note: orNull(inst.note),
    })),
  };
}

// =============================================
// V8 확장 타입 (프로토타입 → 실제 페이지 마이그레이션)
// =============================================

// ===== 증권종류 =====
export type InstrumentType = 'promissory' | 'exchange' | 'cashierCheck' | 'currentCheck';

// ===== 거래방향 (Direction = BillType alias) =====
export type Direction = 'received' | 'issued';

// ===== 매체 =====
export type Medium = 'electronic' | 'paper';

// ===== 이력 레코드 (V8: 처리구분/상대처 추가) =====
export interface HistoryRecord {
  id: string;
  date: string;
  type: string;        // 처리구분 (HISTORY_TYPE_OPTIONS)
  amount: number;
  counterparty: string; // 상대처
  note: string;
}

// ===== V8 폼 데이터 (전체 ~45개 필드) =====
export interface BillFormData {
  // === 공통 ===
  billNumber: string;
  instrumentType: InstrumentType;
  direction: Direction;
  medium: Medium;
  amount: number;
  issueDate: string;
  maturityDate: string;
  note: string;
  // === 전자어음 (조건: medium=electronic) ===
  electronicBillNo: string;
  registrationOrg: string;
  // === 환어음 (조건: instrumentType=exchange) ===
  drawee: string;
  acceptanceStatus: string;
  acceptanceDate: string;
  // === 받을어음 전용 ===
  vendor: string;
  billCategory: string;
  issuerBank: string;
  endorsement: string;
  endorsementOrder: string;
  storagePlace: string;
  receivedStatus: string;
  isDiscounted: boolean;
  discountDate: string;
  discountBank: string;
  discountRate: number;
  discountAmount: number;
  // 배서양도
  endorsementDate: string;
  endorsee: string;
  endorsementReason: string;
  // 추심
  collectionBank: string;
  collectionRequestDate: string;
  collectionFee: number;
  collectionCompleteDate: string;
  collectionResult: string;
  collectionDepositDate: string;
  collectionDepositAmount: number;
  // === 지급어음 전용 ===
  payee: string;
  settlementBank: string;
  paymentMethod: string;
  issuedStatus: string;
  actualPaymentDate: string;
  // === 공통 ===
  paymentPlace: string;
  paymentPlaceDetail: string;
  // === 개서 ===
  renewalDate: string;
  renewalNewBillNo: string;
  renewalReason: string;
  // === 소구/환매 ===
  recourseDate: string;
  recourseAmount: number;
  recourseTarget: string;
  recourseReason: string;
  buybackDate: string;
  buybackAmount: number;
  buybackBank: string;
  // === 환어음 인수거절 ===
  acceptanceRefusalDate: string;
  acceptanceRefusalReason: string;
  // === 공통 조건부 ===
  isSplit: boolean;
  splitCount: number;
  splitAmount: number;
  dishonoredDate: string;
  dishonoredReason: string;
  // 부도 법적 프로세스
  hasProtest: boolean;
  protestDate: string;
  recourseNoticeDate: string;
  recourseNoticeDeadline: string;
  // === 이력 관리 ===
  installments: HistoryRecord[];
  // === 입출금 계좌 ===
  bankAccountInfo: string;
}

// ===== 초기 폼 데이터 =====
export const INITIAL_BILL_FORM_DATA: BillFormData = {
  billNumber: '', instrumentType: 'promissory', direction: 'received',
  medium: 'paper', amount: 0, issueDate: '', maturityDate: '', note: '',
  electronicBillNo: '', registrationOrg: '',
  drawee: '', acceptanceStatus: '', acceptanceDate: '',
  vendor: '', billCategory: 'commercial', issuerBank: '', endorsement: 'endorsable', endorsementOrder: '1',
  storagePlace: '', receivedStatus: 'stored', isDiscounted: false,
  discountDate: '', discountBank: '', discountRate: 0, discountAmount: 0,
  endorsementDate: '', endorsee: '', endorsementReason: '',
  collectionBank: '', collectionRequestDate: '', collectionFee: 0,
  collectionCompleteDate: '', collectionResult: '', collectionDepositDate: '', collectionDepositAmount: 0,
  payee: '', settlementBank: '', paymentMethod: 'autoTransfer',
  issuedStatus: 'stored', actualPaymentDate: '',
  paymentPlace: '', paymentPlaceDetail: '',
  renewalDate: '', renewalNewBillNo: '', renewalReason: '',
  recourseDate: '', recourseAmount: 0, recourseTarget: '', recourseReason: '',
  buybackDate: '', buybackAmount: 0, buybackBank: '',
  acceptanceRefusalDate: '', acceptanceRefusalReason: '',
  isSplit: false, splitCount: 0, splitAmount: 0,
  dishonoredDate: '', dishonoredReason: '',
  hasProtest: false, protestDate: '', recourseNoticeDate: '', recourseNoticeDeadline: '',
  installments: [], bankAccountInfo: '',
};

// ===== BillApiData → BillFormData 직접 변환 (V8 전체 필드 매핑) =====
export function apiDataToFormData(apiData: BillApiData): BillFormData {
  const pf = (v: string | null | undefined) => v ? parseFloat(v) : 0;

  return {
    ...INITIAL_BILL_FORM_DATA,
    billNumber: apiData.bill_number,
    instrumentType: (apiData.instrument_type as InstrumentType) || 'promissory',
    direction: apiData.bill_type as Direction,
    medium: (apiData.medium as Medium) || (apiData.is_electronic ? 'electronic' : 'paper'),
    amount: parseFloat(apiData.amount),
    issueDate: apiData.issue_date,
    maturityDate: apiData.maturity_date || '',
    note: apiData.note || '',
    // 전자어음
    electronicBillNo: apiData.electronic_bill_no || '',
    registrationOrg: apiData.registration_org || '',
    // 환어음
    drawee: apiData.drawee || '',
    acceptanceStatus: apiData.acceptance_status || '',
    acceptanceDate: apiData.acceptance_date || '',
    acceptanceRefusalDate: apiData.acceptance_refusal_date || '',
    acceptanceRefusalReason: apiData.acceptance_refusal_reason || '',
    // 거래처
    vendor: apiData.bill_type === 'received' && apiData.client_id ? String(apiData.client_id) : '',
    payee: apiData.bill_type === 'issued' && apiData.client_id ? String(apiData.client_id) : '',
    // 받을어음 전용
    billCategory: apiData.bill_category || 'commercial',
    issuerBank: apiData.issuer_bank || '',
    endorsement: apiData.endorsement || 'endorsable',
    endorsementOrder: apiData.endorsement_order || '1',
    storagePlace: apiData.storage_place || '',
    receivedStatus: apiData.bill_type === 'received' ? apiData.status : 'stored',
    isDiscounted: apiData.is_discounted ?? false,
    discountDate: apiData.discount_date || '',
    discountBank: apiData.discount_bank || '',
    discountRate: pf(apiData.discount_rate),
    discountAmount: pf(apiData.discount_amount),
    endorsementDate: apiData.endorsement_date || '',
    endorsee: apiData.endorsee || '',
    endorsementReason: apiData.endorsement_reason || '',
    collectionBank: apiData.collection_bank || '',
    collectionRequestDate: apiData.collection_request_date || '',
    collectionFee: pf(apiData.collection_fee),
    collectionCompleteDate: apiData.collection_complete_date || '',
    collectionResult: apiData.collection_result || '',
    collectionDepositDate: apiData.collection_deposit_date || '',
    collectionDepositAmount: pf(apiData.collection_deposit_amount),
    // 지급어음 전용
    settlementBank: apiData.settlement_bank || '',
    paymentMethod: apiData.payment_method || 'autoTransfer',
    issuedStatus: apiData.bill_type === 'issued' ? apiData.status : 'stored',
    actualPaymentDate: apiData.actual_payment_date || '',
    // 공통
    paymentPlace: apiData.payment_place || '',
    paymentPlaceDetail: apiData.payment_place_detail || '',
    // 개서
    renewalDate: apiData.renewal_date || '',
    renewalNewBillNo: apiData.renewal_new_bill_no || '',
    renewalReason: apiData.renewal_reason || '',
    // 소구/환매
    recourseDate: apiData.recourse_date || '',
    recourseAmount: pf(apiData.recourse_amount),
    recourseTarget: apiData.recourse_target || '',
    recourseReason: apiData.recourse_reason || '',
    buybackDate: apiData.buyback_date || '',
    buybackAmount: pf(apiData.buyback_amount),
    buybackBank: apiData.buyback_bank || '',
    // 부도
    isSplit: apiData.is_split ?? false,
    splitCount: 0,
    splitAmount: 0,
    dishonoredDate: apiData.dishonored_date || '',
    dishonoredReason: apiData.dishonored_reason || '',
    hasProtest: apiData.has_protest ?? false,
    protestDate: apiData.protest_date || '',
    recourseNoticeDate: apiData.recourse_notice_date || '',
    recourseNoticeDeadline: apiData.recourse_notice_deadline || '',
    // 이력
    installments: (apiData.installments || []).map(inst => ({
      id: String(inst.id),
      date: inst.installment_date,
      type: inst.type || 'other',
      amount: parseFloat(inst.amount),
      counterparty: inst.counterparty || '',
      note: inst.note || '',
    })),
    bankAccountInfo: apiData.bank_account_id ? String(apiData.bank_account_id) : '',
  };
}

// ===== BillRecord → BillFormData 변환 (하위호환 유지) =====
export function billRecordToFormData(record: BillRecord): BillFormData {
  return {
    ...INITIAL_BILL_FORM_DATA,
    billNumber: record.billNumber,
    direction: record.billType as Direction,
    amount: record.amount,
    issueDate: record.issueDate,
    maturityDate: record.maturityDate,
    note: record.note,
    receivedStatus: record.billType === 'received' ? record.status : 'stored',
    issuedStatus: record.billType === 'issued' ? record.status : 'stored',
    vendor: record.billType === 'received' ? record.vendorId : '',
    payee: record.billType === 'issued' ? record.vendorId : '',
    installments: record.installments.map(inst => ({
      id: inst.id,
      date: inst.date,
      type: 'other',
      amount: inst.amount,
      counterparty: '',
      note: inst.note,
    })),
  };
}