import dayjs from "dayjs";

export type ParsedRowStatus =
  | "ready"
  | "continuation"
  | "unknown-route"
  | "past"
  | "blocked"
  | "exists"
  | "duplicate";

export type ParsedScheduleRow = {
  key: string;
  line: number;
  raw: string;
  arrival: string;
  route: string;
  nights: number | null;
  content_id: string | null;
  available_from: string;
  available_to: string | null;
  comment: string;
  blocked: boolean;
  status: ParsedRowStatus;
};

const MONTHS = [
  "january",
  "february",
  "march",
  "april",
  "may",
  "june",
  "july",
  "august",
  "september",
  "october",
  "november",
  "december",
];

function parseDate(cell: string): string | null {
  const s = cell.trim();
  const iso = s.match(/^(\d{4})-(\d{2})-(\d{2})$/);
  if (iso) return s;

  const mdy = s.match(/([A-Za-z]+)\s+(\d{1,2}),?\s+(\d{4})/);
  const dmy = s.match(/(\d{1,2})\s+([A-Za-z]+),?\s+(\d{4})/);
  let month = -1;
  let day = 0;
  let year = 0;
  if (mdy) {
    month = MONTHS.findIndex((m) => m.startsWith(mdy[1].toLowerCase().slice(0, 3)));
    day = Number(mdy[2]);
    year = Number(mdy[3]);
  } else if (dmy) {
    month = MONTHS.findIndex((m) => m.startsWith(dmy[2].toLowerCase().slice(0, 3)));
    day = Number(dmy[1]);
    year = Number(dmy[3]);
  }
  if (month < 0 || !day || !year) return null;

  const d = dayjs(new Date(year, month, day));
  return d.isValid() && d.date() === day ? d.format("YYYY-MM-DD") : null;
}

const normalise = (s: string) =>
  s
    .toLowerCase()
    .replace(/[^a-z]+/g, " ")
    .split(" ")
    .filter((w) => w.length > 1 && w !== "atoll" && w !== "itinerary")
    .join(" ");

export function matchContent(
  route: string,
  options: { value: string; label: string }[],
): string | null {
  const r = normalise(route);
  if (!r) return null;
  const sorted = [...options].sort((a, b) => b.label.length - a.label.length);
  return sorted.find((o) => r.includes(normalise(o.label)))?.value ?? null;
}

const nightsIn = (s: string): number | null => {
  const m = s.match(/(\d+)\s*N(?:ights?)?\b/i);
  return m ? Number(m[1]) : null;
};

function matchByNights(
  nights: number | null,
  options: { value: string; label: string }[],
): string | null {
  if (!nights) return null;
  const hits = options.filter((o) => nightsIn(o.label) === nights);
  return hits.length === 1 ? hits[0].value : null;
}

export function parseSchedule(
  text: string,
  options: { value: string; label: string }[],
  existing: { content_id: string; available_from: string | null }[],
): ParsedScheduleRow[] {
  const today = dayjs().startOf("day");
  const existingKeys = new Set(
    existing
      .filter((e) => e.available_from)
      .map((e) => `${e.content_id}|${dayjs(e.available_from).format("YYYY-MM-DD")}`),
  );
  const seen = new Set<string>();
  const rows: ParsedScheduleRow[] = [];

  text.split(/\r?\n/).forEach((rawLine, idx) => {
    const cells = rawLine.split("\t").map((c) => c.replace(/^"|"$/g, "").trim());
    const arrival = parseDate(cells[0] ?? "");
    if (!arrival) return;

    const departure = parseDate(cells[1] ?? "");
    const rest = departure ? cells.slice(2) : cells.slice(1);
    const route = rest[0] ?? "";
    const comment = rest[1] ?? "";
    const flag = rest[2] ?? "";
    const nights =
      nightsIn(route) ?? (departure ? dayjs(departure).diff(dayjs(arrival), "day") || null : null);
    const content_id = route
      ? matchContent(route, options) ?? matchByNights(nights, options)
      : null;
    const blocked = /blocked/i.test(flag) || /blocked/i.test(comment);

    let status: ParsedRowStatus = "ready";
    const dupKey = `${content_id}|${arrival}`;
    if (!route) status = "continuation";
    else if (!content_id || !nights) status = "unknown-route";
    else if (existingKeys.has(dupKey)) status = "exists";
    else if (seen.has(dupKey)) status = "duplicate";
    else if (dayjs(arrival).isBefore(today)) status = "past";
    else if (blocked) status = "blocked";
    if (content_id) seen.add(dupKey);

    rows.push({
      key: `${idx}-${arrival}`,
      line: idx + 1,
      raw: rawLine,
      arrival,
      route,
      nights,
      content_id,
      available_from: arrival,
      available_to:
        departure ?? (nights ? dayjs(arrival).add(nights, "day").format("YYYY-MM-DD") : null),
      comment,
      blocked,
      status,
    });
  });

  return rows;
}
