import { format, getTime, formatDistanceToNow, isValid, parse } from 'date-fns';

type InputValue = Date | string | number | null | undefined;

export function fDate(date: InputValue, newFormat?: string) {
  const fm = newFormat || 'dd/MM/yyyy'; // Default format if none is provided

  // Check for null or undefined
  if (date === null || date === undefined) {
    return ''; // Return an empty string for invalid dates
  }

  // Parse the date
  const parsedDate = new Date(date);

  // Validate the parsed date
  if (!isValid(parsedDate)) {
    console.error('Invalid date:', date);
    return ''; // Return an empty string if the date is invalid
  }

  // Format the valid date
  return format(parsedDate, fm);
}

export function fTime(date: InputValue, newFormat?: string) {
  const fm = newFormat || 'p'; // Default time format

  if (date === null || date === undefined) {
    return ''; // Return an empty string for invalid dates
  }

  const parsedDate = new Date(date);
  return isValid(parsedDate) ? format(parsedDate, fm) : '';
}

export function fDateTime(date: string | number | Date) {
  return format(new Date(date), 'dd MMM yyyy p'); // 'p' adds time in 12-hour format
}

export function fTimestamp(date: InputValue) {
  if (date === null || date === undefined) {
    return ''; // Return an empty string for invalid dates
  }

  const parsedDate = new Date(date);
  return isValid(parsedDate) ? getTime(parsedDate) : '';
}

export function fToNow(date: InputValue) {
  if (date === null || date === undefined) {
    return ''; // Return an empty string for invalid dates
  }

  const parsedDate = new Date(date);
  return isValid(parsedDate)
    ? formatDistanceToNow(parsedDate, { addSuffix: true })
    : '';
}

export function isBetween(
  inputDate: Date | string | number,
  startDate: Date | string | number,
  endDate: Date | string | number
): boolean {
  // Convert input dates to valid Date objects
  const date = new Date(inputDate);
  const start = new Date(startDate);
  const end = new Date(endDate);

  // Validate the parsed dates
  if (!isValid(date) || !isValid(start) || !isValid(end)) {
    console.error('Invalid date:', { inputDate, startDate, endDate });
    return false;
  }

  // Strip time from the dates for comparison
  const dateOnly = new Date(date.toDateString());
  const startOnly = new Date(start.toDateString());
  const endOnly = new Date(end.toDateString());

  // Return true if the date is between start and end
  return dateOnly >= startOnly && dateOnly <= endOnly;
}

export function isAfter(startDate: Date | null, endDate: Date | null) {
  if (startDate === null || endDate === null) {
    return false; // Return false if either date is invalid
  }

  return new Date(startDate).getTime() > new Date(endDate).getTime();
}

export const formatDate = (date: string | number | Date | null) => {
  if (!date) return '';
  return format(new Date(date), 'dd MMM yyyy');
};
