export const errorConverter = (data: any): string => {
  let error =
    "Something went wrong. Please try again or contact support if the problem persists.";

  if (data?.response) {
    console.log("errorConverter response: ", data.response);
    if (
      data.response.status == 400 ||
      data.response.status == 500 ||
      data.response.status == 502 ||
      (data.response.status == 404 && data.response._data.message)
    ) {
      if (data.response._data) {
        return (error = data.response._data.message || data.response._data);
      }
    } else if (data.response._data) {
      return (error = data.response._data.message || data.response._data);
    } else if (data.response.status == 404) {
      return "Server Endpoint Not Found";
    } else if (data.response.status == 502) {
      return "The server is temporarily unavailable. Please try again in a few moments.";
    }
    error = `Error ${data.response.status}: ${JSON.stringify(
      data.response._data
    )}`;
  } else if (data?.message) {
    console.log("converter: ", data);
    error = data?.message;
  }
  return error;
};

export const findServiceProviderIdBySite = (
  type: string,
  serviceProviders: any,
  siteId: string
) => {
  if (type === "service-provider") {
    const result = serviceProviders.find(
      (item: Record<string, any>) => item.siteId === siteId
    );
    if (!result?._id) {
      throw new Error(`Service provider with siteId ${siteId} not found`);
    }
    return result?._id;
  }
  return null;
};

export function calculatePercentageValue(
  amount?: string | number | null,
  percentage?: string | number | null
): number {
  const amountNum = Number(amount);
  const percentageNum = Number(percentage);

  if (
    isNaN(amountNum) ||
    isNaN(percentageNum) ||
    amountNum < 0 ||
    percentageNum < 0 ||
    percentageNum > 100
  ) {
    return 0;
  }
  return (amountNum * percentageNum) / 100;
}

export function formatDateToMonthAndDateOnly(value: string | Date) {
  if (!value) return "";
  const date = new Date(value);
  return new Intl.DateTimeFormat("en", {
    month: "long",
    day: "2-digit",
    timeZone: "Asia/Manila",
  }).format(date);
}

export function toTwoDecimals(value: any): string {
  const num = typeof value === "string" ? Number(value) : Number(value);
  const safeNum = !isNaN(num) && isFinite(num) ? num : 0.0;
  return safeNum.toFixed(2);
}

export function sortTimeSlots(timeSlots: string[]) {
  return timeSlots
    .slice()
    .filter((range) => range && typeof range === "string")
    .sort((a, b) => {
      const startTimeA = a.substring(0, 5);
      const startTimeB = b.substring(0, 5);

      if (startTimeA < startTimeB) {
        return -1;
      }
      if (startTimeA > startTimeB) {
        return 1;
      }
      return 0;
    });
}

export function formatDateString(
  today: Date | string,
  format?: "mm-dd-yyyy" | "dd-mm-yyyy",
  dateRange?: "startDate" | "endDate"
) {
  // Get month, day, and year
  today = typeof today === "string" ? new Date(today) : today;

  let month = today.getMonth() + 1; // Adding 1 because getMonth() returns zero-based index
  let day = today.getDate();
  let year = today.getFullYear();

  // Formatting
  let formattedDate;
  if (format === "mm-dd-yyyy") {
    formattedDate = `${month.toString().padStart(2, "0")}-${day
      .toString()
      .padStart(2, "0")}-${year}`;
  } else if (format === "dd-mm-yyyy") {
    formattedDate = `${day.toString().padStart(2, "0")}-${month
      .toString()
      .padStart(2, "0")}-${year}`;
  } else {
    // default yyyy-mm-dd
    formattedDate = `${year}-${month.toString().padStart(2, "0")}-${day
      .toString()
      .padStart(2, "0")}`;
  }
  return formattedDate;
}

export const generateRefNumber = () => {
  const timestamp = Date.now().toString(36); // Time in base36
  const random = Math.random().toString(36).substring(2, 8); // Random string
  const ref = (timestamp + random).substring(0, 10).toUpperCase();
  return ref;
};
