import type { DashboardPeriod } from "@/types/adminDashboard";

export type DashboardDateRange = {
  from: Date;
  to: Date;
};

export type DashboardPeriodPreset = Exclude<DashboardPeriod, "custom">;

export type DashboardPeriodSelection =
  | { mode: "preset"; preset: DashboardPeriodPreset }
  | { mode: "custom"; from: Date; to: Date };

export function rangeForPreset(preset: DashboardPeriodPreset): DashboardDateRange {
  const to = endOfDay(new Date());
  const from = new Date(to);

  switch (preset) {
    case "day":
      from.setHours(0, 0, 0, 0);
      break;
    case "week":
      from.setDate(from.getDate() - 6);
      from.setHours(0, 0, 0, 0);
      break;
    case "year":
      from.setFullYear(from.getFullYear() - 1);
      from.setHours(0, 0, 0, 0);
      break;
    case "month":
    default:
      from.setDate(from.getDate() - 29);
      from.setHours(0, 0, 0, 0);
      break;
  }

  return { from, to };
}

export function defaultPeriodSelection(): DashboardPeriodSelection {
  return { mode: "preset", preset: "month" };
}

export function selectionToRange(selection: DashboardPeriodSelection): DashboardDateRange {
  if (selection.mode === "custom") {
    return {
      from: startOfDay(selection.from),
      to: endOfDay(selection.to),
    };
  }
  return rangeForPreset(selection.preset);
}

export function formatDateApi(d: Date): string {
  const y = d.getFullYear();
  const m = String(d.getMonth() + 1).padStart(2, "0");
  const day = String(d.getDate()).padStart(2, "0");
  return `${y}-${m}-${day}`;
}

export function formatRangeLabel(from: Date, to: Date): string {
  const opts: Intl.DateTimeFormatOptions = { day: "2-digit", month: "short" };
  const a = from.toLocaleDateString("pt-BR", opts);
  const b = to.toLocaleDateString("pt-BR", opts);
  if (formatDateApi(from) === formatDateApi(to)) return a;
  return `${a} – ${b}`;
}

export function presetLabel(preset: DashboardPeriodPreset): string {
  const map: Record<DashboardPeriodPreset, string> = {
    day: "Hoje",
    week: "Semana",
    month: "Mês",
    year: "Ano",
  };
  return map[preset];
}

function startOfDay(d: Date) {
  const x = new Date(d);
  x.setHours(0, 0, 0, 0);
  return x;
}

function endOfDay(d: Date) {
  const x = new Date(d);
  x.setHours(23, 59, 59, 999);
  return x;
}

export function isSameDay(a: Date, b: Date) {
  return formatDateApi(a) === formatDateApi(b);
}

/** Verifica se o intervalo coincide com um preset (para destacar no UI). */
export function detectPreset(range: DashboardDateRange): DashboardPeriodPreset | null {
  for (const preset of ["day", "week", "month", "year"] as DashboardPeriodPreset[]) {
    const ref = rangeForPreset(preset);
    if (isSameDay(ref.from, range.from) && isSameDay(ref.to, range.to)) {
      return preset;
    }
  }
  return null;
}
