
import dns from "node:dns"
import * as XLSX from 'xlsx';


export const generateSerialNumber = (index, currentPage, pageSize) => {
  return (currentPage - 1) * pageSize + (index + 1);
};

export function getTomorrowDate() {
  const today = new Date();
  const tomorrow = new Date(today);
  tomorrow.setDate(today.getDate() + 1);
  
  // Format the date as YYYY-MM-DD (ISO 8601)
  return tomorrow.toISOString().split('T')[0];
}


export function removeTrailingZeros(value) {
  // Convert the value to a number and then to a string
  let number = parseFloat(value);
  let result = number.toString();

  // Check if the result contains a decimal point
  if (result.includes('.')) {
    // Remove trailing zeros if the decimal part is 0 or 00
    result = result.replace(/(\.\d*?)0+$/, '$1'); // Remove trailing zeros
    result = result.replace(/\.$/, ''); // Remove the decimal point if it's the last character
  }

  return result;
}


 export function getCountdownTimer(utcDateString) {
  // Parse the UTC datetime string into a Date object
  const targetDate = new Date(utcDateString);
  const now = new Date();

  // Calculate the difference in milliseconds
  const difference = targetDate - now;

  if (difference <= 0) {
    return 'The time has passed or is now!';
  }

  // Convert the difference from milliseconds to a more readable format
  const seconds = Math.floor(difference / 1000);
  const minutes = Math.floor(seconds / 60);
  const hours = Math.floor(minutes / 60);
  const days = Math.floor(hours / 24);

  const remainingDays = days;
  const remainingHours = hours % 24;
  const remainingMinutes = minutes % 60;
  const remainingSeconds = seconds % 60;

  return `${remainingDays === 0 ? "": remainingDays+"d"}  ${remainingHours === 0 ? "": remainingHours+"h"} ${remainingMinutes}m ${remainingSeconds}s `;
}


export function bytesToMB(bytes) {
  return (bytes / (1024 * 1024)).toFixed(2); // Convert bytes to MB and limit to 2 decimal places
}


export function startCountdown(utcDateString) {
  // Function to update the countdown
  const updateCountdown = () => {
    const countdown = getCountdownTimer(utcDateString);
    console.log(countdown);
  };

  // Update countdown immediately
  updateCountdown();

  // Set up interval to update countdown every minute (60000 milliseconds)
  setInterval(updateCountdown, 60000);
}

export const getFileNameFromPath = (filePath) => {
  const parts = filePath?.split("/");
  return parts?.[parts?.length - 1];
};

export function debounce(func, delay) {
  let debounceTimer;
  return function (...args) {
    clearTimeout(debounceTimer);
    debounceTimer = setTimeout(() => func.apply(this, args), delay);
  };
}



async function resolveMx(domain, recordType) {
  return new Promise((resolve, reject) => {
      dns.resolveMx(domain, (err, mxRecords) => {
          if (err) {
              reject(err);
              return;
          }
          const addresses = mxRecords.map((mxRecord) => mxRecord.exchange);
          resolve(addresses);
      });
  });
}
// Async function to check email address validity
export async function checkEmailValidity(email) {
  try {
      const domain = email?.split("@")[1];
      const addresses = await resolveMx(domain, "MX");

      if (addresses && addresses?.length > 0) {
          return true;
      }
      return false; // No MX record exists
  } catch (err) {
      return false; // Error occurred
  }
}


// Function to convert timestamp to readable date format in Gulf timezone
export function formatTimestampInGulfTimezone(timestamp) {
  const date = new Date(timestamp);
  const options = { 
      year: 'numeric', 
      month: 'long', 
      day: 'numeric', 
      hour: '2-digit', 
      minute: '2-digit', 
      second: '2-digit', 
      timeZone: 'Asia/Dubai', // Gulf Standard Time (GST) timezone
      timeZoneName: 'short'
  };
  return date.toLocaleDateString('en-GB', options);
}


export function formatDate(dateString) {
  const options = { year: 'numeric', month: 'short', day: 'numeric' };
  const date = new Date(dateString);
  return date.toLocaleDateString('en-US', options);
}

export function calculatePercentage(part, total) {
  if (total === 0) {
    return 0; // To avoid division by zero
  }
  return (part / total) * 100;
}



const getNestedValue = (obj, key) => {
  return key.split('.').reduce((value, part) => {
    return value && value[part] ? value[part] : null;
  }, obj);
};

export const exportToExcel = (data, headers) => {
  const flattenedData = data.map((item) => {
    const newItem = {};
    
    // Loop through customHeaders and get the correct values
    headers.forEach((header) => {
      newItem[header.label] = getNestedValue(item, header.key); // Use the helper function
    });

    return newItem; // Return the new flat object
  });

  // Now pass flattenedData to your Excel library to generate the file
  // Assuming you're using a library like `xlsx` for this part:
  
  const worksheet = XLSX.utils.json_to_sheet(flattenedData);
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");

  // Generate file
  XLSX.writeFile(workbook, "exported_data.xlsx");
};


export const exportToExcelNew = (data, fileName = "exported_data.xlsx") => {
  console.log("Data to export:", data); // Log the data for debugging

  // Ensure the data is not empty
  if (!data || data.length === 0) {
    console.error("No data provided for export.");
    return;
  }

  // Convert the data to a worksheet
  const worksheet = XLSX.utils.json_to_sheet(data);

  // Create a new workbook and append the worksheet to it
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");

  // Ensure file has a valid .xlsx extension
  const fileWithExtension = fileName.endsWith(".xlsx") ? fileName : `${fileName}.xlsx`;

  // Write the workbook to a file
  XLSX.writeFile(workbook, fileWithExtension);
};


export function formatDateToYYYYMMDD(dateString) {
  const date = new Date(dateString);

  // Extract individual date components
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are 0-based
  const day = String(date.getDate()).padStart(2, '0');

  // Combine the formatted parts
  return `${year}-${month}-${day}`;
}