import hotToast from "react-hot-toast";

import type { LocomotiveRecord } from "@/types/trainScheduling";

/**
 * Locomotives can now be scheduled in advance: not-at-origin-yard or
 * already-on-future-schedules is allowed with a warning (only OUT_OF_SERVICE
 * is blocked server-side). This returns the hint to surface in the picker,
 * or null when the locomotive is ready at the origin yard.
 */
export function locomotiveWarning(loco: LocomotiveRecord): string | null {
  const hints: string[] = [];
  if (loco.atOriginYard === false) hints.push("not at origin yard");
  const futureCount = loco.futureScheduleCount ?? 0;
  if (futureCount > 0) {
    hints.push(`on ${futureCount} future schedule${futureCount === 1 ? "" : "s"}`);
  }
  return hints.length ? hints.join(" · ") : null;
}

/** MultiSelect option for the schedule-creation locomotive picker. */
export function locomotiveOption(
  loco: LocomotiveRecord,
  nameSeparator = " — ",
): { value: string; label: string } {
  const base = `${loco.code}${loco.name ? `${nameSeparator}${loco.name}` : ""}`;
  const warning = locomotiveWarning(loco);
  return {
    value: loco.id,
    label: warning ? `${base} · ⚠ ${warning}` : base,
  };
}

/**
 * Yellow toast listing create-schedule warnings (e.g. locomotive not at the
 * origin yard yet). The shared `useToast` hook only knows success/error, so
 * this styles a react-hot-toast directly.
 */
export function showScheduleWarnings(warnings?: string[] | null): void {
  if (!warnings?.length) return;
  hotToast(warnings.join("\n"), {
    icon: "⚠️",
    duration: 8000,
    style: {
      background: "var(--mantine-color-yellow-0)",
      color: "var(--mantine-color-yellow-9)",
      border: "1px solid var(--mantine-color-yellow-4)",
    },
  });
}
