// ===== 어음 구분 =====
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;
  installment_date: string;
  amount: string;
  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;
  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[];
}

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 변환 함수 =====
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;
  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;
}