import DateObject from "react-date-object";
import gregorian from "react-date-object/calendars/gregorian";
import persian from "react-date-object/calendars/persian";
import gregorian_en from "react-date-object/locales/gregorian_en";
import persian_fa from "react-date-object/locales/persian_fa";

export const parseApiDate = (value?: string | null): DateObject | null => {
  if (!value) return null;
  const date = new DateObject({ date: value, calendar: gregorian });
  return date.isValid ? date : null;
};

export const toApiDate = (date: DateObject): string => {
  return date.convert(gregorian, gregorian_en).format("YYYY-MM-DD");
};

export const formatDateLabel = (date: DateObject | null) => {
  if (!date) return "";
  return date.convert(persian, persian_fa).format("D MMMM");
};

export const formatDateRange = (startDate: DateObject | null, endDate: DateObject | null) => {
  const start = formatDateLabel(startDate);
  const end = formatDateLabel(endDate);

  if (start && end) return `${start} - ${end}`;
  return start || end;
};
