import { format, parseISO, isValid, startOfDay } from 'date-fns';
import { de } from 'date-fns/locale';

export const parseDateValue = (value) => {
  if (!value) {
    return null;
  }
  const parsed = parseISO(value);
  return isValid(parsed) ? parsed : null;
};

export const formatDateValue = (date) => {
  if (!(date instanceof Date) || !isValid(date)) {
    return null;
  }
  return format(date, 'yyyy-MM-dd');
};

export const formatRangeLabel = (start, end) => {
  const startDate = parseDateValue(start);
  const endDate = parseDateValue(end);
  if (startDate && endDate) {
    const startLabel = format(startDate, 'dd.MM.yyyy', { locale: de });
    const endLabel = format(endDate, 'dd.MM.yyyy', { locale: de });
    if (startLabel === endLabel) {
      return startLabel;
    }
    return `${startLabel} – ${endLabel}`;
  }
  if (startDate) {
    return format(startDate, 'dd.MM.yyyy', { locale: de });
  }
  return 'Zeitraum auswählen';
};

export const buildSelectionRange = (start, end, minDate) => {
  const minimum = minDate || startOfDay(new Date());
  let startDate = parseDateValue(start) || parseDateValue(end) || minimum;
  let endDate = parseDateValue(end) || parseDateValue(start) || startDate;
  if (startDate < minimum) {
    startDate = minimum;
  }
  if (endDate < minimum) {
    endDate = startDate;
  }
  return {
    startDate,
    endDate,
    key: 'selection'
  };
};
