import moment from "moment-jalaali";
import dayjs from "@/utils/dayjs";

try {
  moment.loadPersian({ dialect: "persian-modern", usePersianDigits: false });
} catch {
  /* already loaded */
}

/** نمایش تاریخ شمسی — پیش‌فرض: ۱۴۰۴/۰۴/۲۵ */
export function formatJalali(date: unknown, format = "jYYYY/jMM/jDD") {
  if (!date) return "";
  const m = moment(date as moment.MomentInput);
  return m.isValid() ? m.format(format) : "";
}

/** نمایش تاریخ+ساعت شمسی */
export function formatJalaliDateTime(
  date: unknown,
  timeFormat = "HH:mm",
  utc = false,
) {
  if (!date) return "";
  const m = utc ? moment.utc(date as string).local() : moment(date as moment.MomentInput);
  if (!m.isValid()) return "";
  return m.format(`jYYYY/jMM/jDD ${timeFormat}`);
}

/** نام روز هفته به انگلیسی (برای API برنامه کاری فروشگاه) */
export function gregorianWeekdayLower(date: unknown = new Date()) {
  return dayjs(date as string | Date)
    .calendar("gregory")
    .locale("en")
    .format("dddd")
    .toLowerCase();
}

export function fromApiDate(value: unknown) {
  if (value == null || value === "") return null;
  if (dayjs.isDayjs?.(value as dayjs.Dayjs)) return value as dayjs.Dayjs;
  return dayjs(value as string | Date | number);
}

export function toApiDate(value: unknown, format = "YYYY-MM-DD") {
  if (value == null || value === "") return null;
  if (typeof value === "string") {
    if (/^\d{4}-\d{2}-\d{2}/.test(value) && !/^(13|14)\d{2}/.test(value)) {
      return moment(value).format(format);
    }
    if (/^(13|14)\d{2}[-/]\d{1,2}[-/]\d{1,2}/.test(value)) {
      const normalized = value.replace(/\//g, "-");
      return moment(normalized, ["jYYYY-jMM-jDD", "jYYYY-jM-jD"]).format(format);
    }
  }
  if (dayjs.isDayjs?.(value as dayjs.Dayjs) || (value && typeof (value as { calendar?: unknown }).calendar === "function")) {
    return dayjs(value as dayjs.Dayjs).calendar("gregory").format(format);
  }
  const d =
    (value as { toDate?: () => Date })?.toDate?.() ||
    (value as { $d?: Date })?.$d ||
    value;
  const m = moment(d as moment.MomentInput);
  return m.isValid() ? m.format(format) : null;
}

export function toApiDateTime(value: unknown, format = "YYYY-MM-DD HH:mm") {
  return toApiDate(value, format);
}

/** متن نمایش تاریخ در سرچ — همیشه شمسی با اسلش */
export function formatSearchDate(value?: Date | string | null) {
  if (value == null || value === "") return "";
  if (typeof value === "string") {
    const trimmed = value.trim();
    if (/^(13|14)\d{2}[/.-]\d{1,2}[/.-]\d{1,2}/.test(trimmed)) {
      const m = moment(trimmed.replace(/\//g, "-"), ["jYYYY-jMM-jDD", "jYYYY-jM-jD"], true);
      return m.isValid() ? m.format("jYYYY/jMM/jDD") : "";
    }
    if (/^\d{4}-\d{2}-\d{2}/.test(trimmed) && !/^(13|14)/.test(trimmed)) {
      const m = moment(trimmed.slice(0, 10), "YYYY-MM-DD", true);
      return m.isValid() ? m.format("jYYYY/jMM/jDD") : "";
    }
  }
  const m = moment(value as moment.MomentInput);
  return m.isValid() ? m.format("jYYYY/jMM/jDD") : "";
}

/** پارس تاریخ سرچ (شمسی یا میلادی) → dayjs معتبر */
export function parseSearchDate(query?: string | null) {
  if (!query) return null;
  const trimmed = String(query).trim();
  if (/^(13|14)\d{2}[/.-]\d{1,2}[/.-]\d{1,2}/.test(trimmed)) {
    const m = moment(trimmed.replace(/\//g, "-"), ["jYYYY-jMM-jDD", "jYYYY-jM-jD"], true);
    return m.isValid() ? dayjs(m.toDate()) : null;
  }
  if (/^\d{4}-\d{2}-\d{2}/.test(trimmed) && !/^(13|14)/.test(trimmed)) {
    const m = moment(trimmed.slice(0, 10), "YYYY-MM-DD", true);
    return m.isValid() ? dayjs(m.toDate()) : null;
  }
  const m = moment(trimmed);
  return m.isValid() ? dayjs(m.toDate()) : null;
}

export { moment };
