import { format, formatDistanceToNowStrict, isToday, isTomorrow, isYesterday } from "date-fns";
import { id as localeId } from "date-fns/locale";

/** Locale-aware date/time formatting helpers (Indonesian). */

export function formatDate(date: Date | string | null | undefined): string {
  if (!date) return "—";
  return format(new Date(date), "d MMM yyyy", { locale: localeId });
}

export function formatDateTime(date: Date | string | null | undefined): string {
  if (!date) return "—";
  return format(new Date(date), "d MMM yyyy, HH:mm", { locale: localeId });
}

export function formatTime(date: Date | string | null | undefined): string {
  if (!date) return "—";
  return format(new Date(date), "HH:mm", { locale: localeId });
}

export function formatDayName(date: Date | string): string {
  return format(new Date(date), "EEEE", { locale: localeId });
}

/** "Hari ini", "Besok", "Kemarin", or a formatted date. */
export function formatRelativeDay(date: Date | string | null | undefined): string {
  if (!date) return "—";
  const value = new Date(date);
  if (isToday(value)) return "Hari ini";
  if (isTomorrow(value)) return "Besok";
  if (isYesterday(value)) return "Kemarin";
  return formatDate(value);
}

/** "3 hari lalu" style relative time. */
export function formatRelativeTime(date: Date | string | null | undefined): string {
  if (!date) return "—";
  return `${formatDistanceToNowStrict(new Date(date), { locale: localeId, addSuffix: true })}`;
}

export interface DueInfo {
  label: string;
  tone: "danger" | "warning" | "neutral" | "success";
  overdue: boolean;
  daysLeft: number;
}

/** Human-readable deadline state used across assignment lists. */
export function describeDueDate(dueAt: Date | string | null | undefined): DueInfo | null {
  if (!dueAt) return null;
  const due = new Date(dueAt);
  const diffMs = due.getTime() - Date.now();
  const daysLeft = Math.ceil(diffMs / (24 * 60 * 60 * 1000));

  if (diffMs < 0) {
    return {
      label: `Terlewat ${formatRelativeTime(due)}`,
      tone: "danger",
      overdue: true,
      daysLeft,
    };
  }
  if (daysLeft <= 1) {
    return { label: isToday(due) ? `Hari ini, ${formatTime(due)}` : `Besok, ${formatTime(due)}`, tone: "warning", overdue: false, daysLeft };
  }
  if (daysLeft <= 3) {
    return { label: `${daysLeft} hari lagi`, tone: "warning", overdue: false, daysLeft };
  }
  return { label: formatDate(due), tone: "neutral", overdue: false, daysLeft };
}

export function formatNumber(value: number): string {
  return new Intl.NumberFormat("id-ID").format(value);
}

export function formatPercent(value: number | null | undefined, digits = 0): string {
  if (value === null || value === undefined) return "—";
  return `${value.toFixed(digits)}%`;
}

export function formatScore(score: number | null, maxScore: number): string {
  if (score === null) return "—";
  return `${score} / ${maxScore}`;
}

/**
 * Minutes → "45 menit" / "1 jam 15 menit" / "8 hari".
 *
 * Minutes alone stop being readable surprisingly fast: an attempt stored as
 * "11520 mnt" is eight days, and a table that prints the raw count gives no
 * hint that anything is wrong. Days make an impossible value obvious at a
 * glance.
 */
export function formatDuration(minutes: number | null | undefined): string {
  if (minutes === null || minutes === undefined) return "—";
  if (minutes < 60) return `${minutes} menit`;

  if (minutes < 24 * 60) {
    const hours = Math.floor(minutes / 60);
    const rest = minutes % 60;
    return rest === 0 ? `${hours} jam` : `${hours} jam ${rest} menit`;
  }

  const days = Math.floor(minutes / (24 * 60));
  const restHours = Math.floor((minutes % (24 * 60)) / 60);
  return restHours === 0 ? `${days} hari` : `${days} hari ${restHours} jam`;
}

export function formatFileSize(bytes: number | null | undefined): string {
  if (!bytes) return "—";
  const units = ["B", "KB", "MB", "GB"];
  let value = bytes;
  let unitIndex = 0;
  while (value >= 1024 && unitIndex < units.length - 1) {
    value /= 1024;
    unitIndex += 1;
  }
  return `${value.toFixed(value < 10 && unitIndex > 0 ? 1 : 0)} ${units[unitIndex]}`;
}

/** Greeting keyed to the current hour, in Indonesian. */
export function greeting(date = new Date()): string {
  const hour = date.getHours();
  if (hour < 11) return "Selamat pagi";
  if (hour < 15) return "Selamat siang";
  if (hour < 19) return "Selamat sore";
  return "Selamat malam";
}

/**
 * Build a download URL for a stored file (a submission id or a storage key).
 *
 * The trailing `/download` segment is not decorative. The host in front of this
 * app answers any request whose last path segment has a file extension — the
 * shape a storage key almost always has — with its own 404 and never reaches
 * Next.js, so the bare URL would fail for every real attachment. Appending a
 * final segment without an extension gets the request through to the route,
 * which strips it again. Every download link must go through this helper.
 */
export function fileHref(idOrKey: string): string {
  return `/api/files/${idOrKey}/download`;
}
