// utils/dateHelpers.ts
export const getDaysRemaining = (endDate: string): number => {
  const today = new Date();
  const eventEndDate = new Date(endDate);
  today.setHours(0, 0, 0, 0);
  eventEndDate.setHours(0, 0, 0, 0);

  const timeDiff = eventEndDate.getTime() - today.getTime();
  const daysRemaining = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));

  return daysRemaining;
};

export const calculateDuration = (
  startDate: string,
  endDate: string
): number => {
  if (!startDate || !endDate) return 14;

  const start = new Date(startDate);
  const end = new Date(endDate);
  const diffTime = Math.abs(end.getTime() - start.getTime());
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

  return diffDays || 14;
};

export const formatDate = (dateString: string): string => {
  if (!dateString) return "Date not set";

  const date = new Date(dateString);
  const day = date.getDate();
  const month = date.toLocaleString("en-US", { month: "long" });
  const year = date.getFullYear();

  // Add ordinal suffix to day
  const getOrdinalSuffix = (day: number) => {
    if (day > 3 && day < 21) return "th";
    switch (day % 10) {
      case 1:
        return "st";
      case 2:
        return "nd";
      case 3:
        return "rd";
      default:
        return "th";
    }
  };

  return `${day}${getOrdinalSuffix(day)} ${month} ${year}`;
};

export const calculateTotalPriceForAllEvents = (events: any[]): string => {
  if (!events || events.length === 0) return "0,00";

  const total = events.reduce((sum, event) => {
    const pricePerDay = event.price || 1;
    return sum + pricePerDay;
  }, 0);

  return total.toFixed(2).replace(".", ",");
};

export const normalizePrice = (price: string | number): number => {
  if (typeof price === "number") {
    return price;
  }

  const normalizedString = price.replace(",", ".");
  const parsedValue = parseFloat(normalizedString);

  return isNaN(parsedValue) ? 0 : parsedValue;
};
export const calculateStartDateFromDays = (
  endDate: string,
  selectedDays: number
): string => {
  if (!endDate || !selectedDays || selectedDays <= 0) {
    return "";
  }

  try {
    const end = new Date(endDate);
    const start = new Date(end);
    start.setDate(end.getDate() - selectedDays + 1);

    const year = start.getFullYear();
    const month = String(start.getMonth() + 1).padStart(2, "0");
    const day = String(start.getDate()).padStart(2, "0");

    return `${year}-${month}-${day}`;
  } catch (error) {
    console.error("Error calculating start date:", error);
    return "";
  }
};

export const validateDate = (dateString: string): string => {
  if (!dateString) return "Date is required";

  if (/^\d{4}-\d{2}-\d{2}$/.test(dateString)) {
    const date = new Date(dateString);
    if (isNaN(date.getTime())) {
      return "Invalid date";
    }
    return "";
  }
  const date = new Date(dateString);
  if (isNaN(date.getTime())) {
    return "Please enter a valid date (YYYY-MM-DD)";
  }

  return "";
};

export const formatEventDisplay = (event: any, index: number): string => {
  const maxCommuneLength = 20;
  const maxTitleLength = 25;

  let locationText = event.commune;
  if (locationText.length > maxCommuneLength) {
    locationText = locationText.substring(0, maxCommuneLength) + "...";
  }

  let titleText = event.title || "";
  if (titleText && titleText.length > maxTitleLength) {
    titleText = titleText.substring(0, maxTitleLength) + "...";
  }

  if (titleText && titleText !== event.commune) {
    return `${index + 1}. ${locationText}:${event.postcode}- ${titleText}`;
  }

  return `${index + 1}. ${locationText} - ${event.postcode}`;
};
export const calculateDaysRemaining = (endDate: string) => {
  const end = new Date(endDate);
  const today = new Date();
  const diffTime = end.getTime() - today.getTime();
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
  return diffDays > 0 ? diffDays : 0;
};

export const calculatePaidDays = (startDate: string, endDate: string) => {
  const start = new Date(startDate);
  const end = new Date(endDate);
  const diffTime = end.getTime() - start.getTime();
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
  return diffDays + 1; // +1 to include both start and end dates
};

export const isValidUrl = (urlString: any): boolean => {
  try {
    // Try to create a URL object - this is the most reliable method
    new URL(urlString);
    return true;
  } catch {
    // If that fails, check if it's a valid domain pattern
    const domainPattern =
      /^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*\.[a-zA-Z]{2,}$/;

    // Check if it's a domain without protocol
    if (domainPattern.test(urlString) && !urlString.includes(" ")) {
      return true;
    }

    return false;
  }
};

export const formatDateForInput = (
  dateString: string | null | undefined
): string => {
  if (!dateString) return "";

  try {
    // If already in YYYY-MM-DD format, return as is
    if (/^\d{4}-\d{2}-\d{2}$/.test(dateString)) {
      return dateString;
    }

    // Parse the date and format it as YYYY-MM-DD
    const date = new Date(dateString);
    if (isNaN(date.getTime())) {
      return "";
    }

    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");

    return `${year}-${month}-${day}`;
  } catch (error) {
    console.error("Error formatting date for input:", error);
    return "";
  }
};
