import moment from "moment";
import { toWesternDigits } from "@/lib/digits";

/** Approved client review, 25 Oct 2026. All wall-clock schedules are in Kuwait. */
export interface ReviewSchedule {
  start_at?: string | null;
  end_at?: string | null;
  start_date?: string | null;
  end_date?: string | null;
  start_time?: string | null;
  end_time?: string | null;
  opportunity_status?: string | null;
  time_slots?: ReadonlyArray<{ date?: string | null; start_time?: string | null; end_time?: string | null }> | null;
  timeslots_display?: ReadonlyArray<{ date?: string | null; start_time?: string | null; end_time?: string | null }> | null;
}

/** An empty legacy array must not hide the populated development schedule. */
export function reviewScheduleSlots(item: ReviewSchedule) {
  return item.time_slots?.length ? item.time_slots : item.timeslots_display ?? [];
}

/** Offset-free API timestamps are Kuwait wall time, never the browser's zone. */
export function parseKuwaitInstant(value?: string | null): moment.Moment | null {
  if (!value) return null;
  const normalized = value.trim().replace(" ", "T");
  const withZone = /(?:Z|[+-]\d{2}:?\d{2})$/i.test(normalized) ? normalized
    : `${normalized.length === 10 ? `${normalized}T00:00:00` : normalized}+03:00`;
  const parsed = moment.parseZone(withZone, moment.ISO_8601, true).utcOffset(180);
  return parsed.isValid() ? parsed : null;
}

export function isOpportunityCancelled(item?: ReviewSchedule | null): boolean {
  return item?.opportunity_status === "cancelled";
}

function instant(date?: string | null, time?: string | null, end = false): moment.Moment | null {
  if (!date) return null;
  const day = date.slice(0, 10);
  const embeddedTime = date.length > 10 ? date.slice(11, 19) : "";
  const value = moment.parseZone(`${day}T${time || embeddedTime || (end ? "23:59:59" : "00:00:00")}+03:00`);
  return value.isValid() ? value : null;
}

export function opportunityStartsAt(item?: ReviewSchedule | null): moment.Moment | null {
  if (!item) return null;
  const explicit = parseKuwaitInstant(item.start_at);
  if (explicit) return explicit;
  const slots = reviewScheduleSlots(item);
  const starts = slots.map(s => instant(s.date, s.start_time || item.start_time)).filter((s): s is moment.Moment => s !== null);
  return starts.length ? moment.min(starts) : instant(item.start_date, item.start_time);
}

export function opportunityEndsAt(item?: ReviewSchedule | null): moment.Moment | null {
  if (!item) return null;
  const explicit = parseKuwaitInstant(item.end_at);
  if (explicit) return explicit;
  const slots = reviewScheduleSlots(item);
  const ends = slots.map(s => {
    const end = instant(s.date, s.end_time || item.end_time, true);
    const start = instant(s.date, s.start_time || item.start_time);
    return end && start && end.isSameOrBefore(start) ? end.add(1, "day") : end;
  }).filter((s): s is moment.Moment => s !== null);
  if (ends.length) return moment.max(ends);
  const end = instant(item.end_date ?? item.start_date, item.end_time, true);
  const start = instant(item.start_date, item.start_time);
  return end && start && end.isBefore(start) ? end.add(1, "day") : end;
}

export function hasOpportunityStarted(item?: ReviewSchedule | null, now = moment()): boolean {
  const start = opportunityStartsAt(item);
  return start ? now.isSameOrAfter(start) : ["inprogress", "completed"].includes(item?.opportunity_status ?? "");
}

export function hasOpportunityEnded(item?: ReviewSchedule | null, now = moment()): boolean {
  const end = opportunityEndsAt(item);
  return end ? now.isSameOrAfter(end) : item?.opportunity_status === "completed";
}

export function isBeforeCancellationCutoff(item?: ReviewSchedule | null, now = moment()): boolean {
  const start = opportunityStartsAt(item);
  return Boolean(!isOpportunityCancelled(item) && start && now.isSameOrBefore(start.clone().subtract(24, "hours")));
}

/** The API must persist actual minute-accurate hours; the UI never credits a schedule. */
export function formatHoursMinutes(value: number | string | null | undefined): string {
  // Arabic-Indic digits and the Arabic decimal separator «٫» (`٢٫٥`) both parse.
  const number = Number(toWesternDigits(value ?? 0).trim() || 0);
  const minutes = Number.isFinite(number) ? Math.max(0, Math.round(number * 60)) : 0;
  return `${Math.floor(minutes / 60)}:${String(minutes % 60).padStart(2, "0")}`;
}

export const REVIEW_DEFAULT_PLATFORM_FEE = 30;
export const REVIEW_CHECKOUT_TTL_MINUTES = 5;
export const REVIEW_MAX_MANUAL_HOURS = 24;

/** H:MM is the UI format; decimals are accepted for legacy callers. */
export function parseHoursInput(raw: string): number | null {
  const value = toWesternDigits(raw).trim();
  const match = /^(\d{1,2}):([0-5]\d)$/.exec(value);
  const minutes = match ? Number(match[1]) * 60 + Number(match[2]) : value && Number.isFinite(Number(value)) ? Math.round(Number(value) * 60) : -1;
  return minutes >= 0 && minutes <= 1440 ? minutes / 60 : null;
}
