import {
  isMothershipWeekendIso,
  parseIsoDateLocal,
  toIsoDateLocal,
} from "@/lib/mothership/logged-in-constraints";

export type MothershipWeekdayCell = {
  iso: string;
  day: number;
  inMonth: boolean;
  disabled: boolean;
  isWeekend: boolean;
  isPast: boolean;
  isSelected: boolean;
};

export function isMothershipDateSelectable(
  iso: string,
  minIso: string,
): boolean {
  const d = parseIsoDateLocal(iso);
  const min = parseIsoDateLocal(minIso);
  if (!d || !min) return false;
  if (isMothershipWeekendIso(iso)) return false;
  return d.getTime() >= min.getTime();
}

export function buildMothershipWeekdayGrid(
  year: number,
  month: number,
  selectedIso: string | undefined,
  minIso: string,
): MothershipWeekdayCell[] {
  const first = new Date(year, month, 1, 12, 0, 0);
  const startPad = first.getDay();
  const daysInMonth = new Date(year, month + 1, 0).getDate();
  const cells: MothershipWeekdayCell[] = [];

  for (let i = 0; i < startPad; i += 1) {
    const d = new Date(year, month, -(startPad - 1 - i), 12, 0, 0);
    const iso = toIsoDateLocal(d);
    cells.push({
      iso,
      day: d.getDate(),
      inMonth: false,
      disabled: true,
      isWeekend: isMothershipWeekendIso(iso),
      isPast: true,
      isSelected: false,
    });
  }

  for (let day = 1; day <= daysInMonth; day += 1) {
    const d = new Date(year, month, day, 12, 0, 0);
    const iso = toIsoDateLocal(d);
    const weekend = isMothershipWeekendIso(iso);
    const selectable = isMothershipDateSelectable(iso, minIso);
    cells.push({
      iso,
      day,
      inMonth: true,
      disabled: !selectable,
      isWeekend: weekend,
      isPast: !selectable && !weekend,
      isSelected: selectedIso === iso,
    });
  }

  while (cells.length % 7 !== 0) {
    const last = cells[cells.length - 1]!;
    const d = parseIsoDateLocal(last.iso)!;
    d.setDate(d.getDate() + 1);
    const iso = toIsoDateLocal(d);
    cells.push({
      iso,
      day: d.getDate(),
      inMonth: false,
      disabled: true,
      isWeekend: isMothershipWeekendIso(iso),
      isPast: true,
      isSelected: false,
    });
  }

  return cells;
}

export function formatMothershipWeekdayDateLabel(iso: string): string {
  const d = parseIsoDateLocal(iso);
  if (!d) return iso;
  const wd = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"][
    d.getDay()
  ]!;
  const yyyy = d.getFullYear();
  const mm = String(d.getMonth() + 1).padStart(2, "0");
  const dd = String(d.getDate()).padStart(2, "0");
  return `${yyyy}-${mm}-${dd}（${wd}）`;
}

export function monthLabelZh(year: number, month: number): string {
  return `${year}年${month + 1}月`;
}
