/**
 * Utility functions for Transfer Payment Bill module
 */

/**
 * Format currency amount to Vietnamese format
 * @param {number} amount - Amount to format
 * @returns {string} - Formatted currency string
 */
export function formatCurrency(amount) {
  if (amount === null || amount === undefined || isNaN(amount)) {
    return "0đ";
  }

  return new Intl.NumberFormat("vi-VN", {
    style: "currency",
    currency: "VND",
    minimumFractionDigits: 0,
    maximumFractionDigits: 0,
  }).format(amount);
}

/**
 * Format date to Vietnamese format
 * @param {string|Date} date - Date to format
 * @param {boolean} includeTime - Whether to include time
 * @returns {string} - Formatted date string
 */
export function formatDate(date, includeTime = false) {
  if (!date) return "";

  const dateObj = typeof date === "string" ? new Date(date) : date;

  if (isNaN(dateObj.getTime())) return "";

  // Check for default/empty date (0001-01-01)
  if (dateObj.getFullYear() === 1) return "";

  const options = {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    timeZone: "Asia/Ho_Chi_Minh",
  };

  if (includeTime) {
    options.hour = "2-digit";
    options.minute = "2-digit";
    options.hour12 = false;
  }

  return dateObj.toLocaleDateString("vi-VN", options);
}

/**
 * Format date for API (ISO format)
 * @param {Date} date - Date to format
 * @returns {string} - ISO formatted date string
 */
export function formatDateForAPI(date) {
  if (!date) return "";

  const dateObj = typeof date === "string" ? new Date(date) : date;

  if (isNaN(dateObj.getTime())) return "";

  return dateObj.toISOString();
}

/**
 * Get status color class
 * @param {string} status - Status value
 * @returns {string} - CSS class for status color
 */
export function getStatusColorClass(status) {
  const statusColors = {
    Draft: "text-info",
    Approved: "text-success",
    Cancelled: "text-danger",
  };

  return statusColors[status] || "text-secondary";
}

/**
 * Get priority color class
 * @param {string} priority - Priority value
 * @returns {string} - CSS class for priority color
 */
export function getPriorityColorClass(priority) {
  const priorityColors = {
    Low: "text-muted",
    Medium: "text-info",
    High: "text-warning",
    Urgent: "text-danger",
  };

  return priorityColors[priority] || "text-secondary";
}

/**
 * Validate email format
 * @param {string} email - Email to validate
 * @returns {boolean} - Whether email is valid
 */
export function isValidEmail(email) {
  if (!email) return false;

  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
}

/**
 * Validate phone number format (Vietnamese)
 * @param {string} phone - Phone number to validate
 * @returns {boolean} - Whether phone number is valid
 */
export function isValidPhone(phone) {
  if (!phone) return false;

  // Vietnamese phone number patterns
  const phoneRegex = /^(0|\+84)[3|5|7|8|9][0-9]{8}$/;
  return phoneRegex.test(phone.replace(/\s/g, ""));
}

/**
 * Generate SmartTable search model
 * @param {number} page - Page number
 * @param {number} pageSize - Page size
 * @param {string} searchText - Search text
 * @param {Object} filters - Additional filters
 * @returns {Object} - SmartTable search model
 */
export function createSmartTableModel(
  page = 1,
  pageSize = 25,
  searchText = "",
  filters = {}
) {
  return {
    page: page,
    pageSize: pageSize,
    search: {
      predicateObject: searchText,
    },
    sorts: [],
    ...filters,
  };
}

/**
 * Debounce function for search input
 * @param {Function} func - Function to debounce
 * @param {number} delay - Delay in milliseconds
 * @returns {Function} - Debounced function
 */
export function debounce(func, delay) {
  let timeoutId;
  return function (...args) {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => func.apply(this, args), delay);
  };
}

/**
 * Calculate total amount from selected orders
 * @param {Array} orders - Array of orders
 * @param {Array} selectedIds - Array of selected order IDs
 * @returns {number} - Total transfer fee amount
 */
export function calculateTotalTransferFee(orders, selectedIds) {
  if (!orders || !selectedIds || selectedIds.length === 0) {
    return 0;
  }

  return orders
    .filter((order) => selectedIds.includes(order.orderId))
    .reduce((total, order) => total + (order.transferFeeAmount || 0), 0);
}

/**
 * Check if user can perform action based on permissions
 * @param {Object} permissions - Permission object
 * @param {string} action - Action to check
 * @returns {boolean} - Whether user can perform action
 */
export function canPerformAction(permissions, action) {
  if (!permissions) return false;

  const actionMap = {
    view: true, // Always allow view if permissions object exists
    edit: permissions.canEdit,
    cancel: permissions.canCancel,
    approve: permissions.canApprove,
  };

  return actionMap[action] || false;
}

/**
 * Get display text for status
 * @param {string} status - Status value
 * @returns {string} - Display text
 */
export function getStatusDisplayText(status) {
  const statusTexts = {
    Draft: "Nháp",
    Approved: "Đã duyệt",
    Cancelled: "Đã hủy",
  };

  return statusTexts[status] || status;
}

/**
 * Get display text for priority
 * @param {string} priority - Priority value
 * @returns {string} - Display text
 */
export function getPriorityDisplayText(priority) {
  const priorityTexts = {
    Low: "Thấp",
    Medium: "Trung bình",
    High: "Cao",
    Urgent: "Khẩn cấp",
  };

  return priorityTexts[priority] || priority;
}

/**
 * Map status number to status string for components
 * @param {number} statusNumber - Status number from API
 * @returns {string} - Status string for components
 */
export function mapStatusNumberToString(statusNumber) {
  const statusMapping = {
    1: "Draft", // Nháp
    2: "Approved", // Đã duyệt
    8: "Cancelled", // Đã hủy
  };

  return statusMapping[statusNumber] || "Draft";
}

/**
 * Map priority number to priority string for components
 * @param {number} priorityNumber - Priority number from API
 * @returns {string} - Priority string for components
 */
export function mapPriorityNumberToString(priorityNumber) {
  const priorityMapping = {
    1: "Low", // Thấp
    2: "Medium", // Trung bình
    3: "High", // Cao
    4: "Urgent", // Khẩn cấp
  };

  return priorityMapping[priorityNumber] || "Low";
}
