import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";

// Fusion intelligente des classes Tailwind (utilisée par shadcn)
export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}

// Formatage monétaire (par défaut MAD - Dirham marocain)
export function formatMoney(amount: number, devise: string = "MAD"): string {
  return new Intl.NumberFormat("fr-FR", {
    style: "currency",
    currency: devise,
    minimumFractionDigits: 2,
  }).format(amount);
}

// Formatage de date en français
export function formatDate(date: Date | string, withTime: boolean = false): string {
  const d = typeof date === "string" ? new Date(date) : date;
  if (withTime) {
    return d.toLocaleString("fr-FR", {
      day: "2-digit",
      month: "2-digit",
      year: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    });
  }
  return d.toLocaleDateString("fr-FR", {
    day: "2-digit",
    month: "2-digit",
    year: "numeric",
  });
}

// Date au format ISO pour les input type="date"
export function toInputDate(date: Date | string): string {
  const d = typeof date === "string" ? new Date(date) : date;
  return d.toISOString().split("T")[0];
}

// Calcul du nombre de nuits entre deux dates
export function calculateNights(arrivee: Date | string, depart: Date | string): number {
  const a = typeof arrivee === "string" ? new Date(arrivee) : arrivee;
  const d = typeof depart === "string" ? new Date(depart) : depart;
  const diff = d.getTime() - a.getTime();
  return Math.max(1, Math.ceil(diff / (1000 * 60 * 60 * 24)));
}

// Parser les champs JSON stockés en string (SQLite ne supporte pas JSON natif)
export function parseJsonField<T>(value: string | null | undefined, fallback: T): T {
  if (!value) return fallback;
  try {
    return JSON.parse(value) as T;
  } catch {
    return fallback;
  }
}

// Génération d'un numéro de facture (F-0001, F-0002...)
export function generateInvoiceNumber(currentCount: number): string {
  return `F-${String(currentCount + 1).padStart(4, "0")}`;
}

// Vérification des permissions par rôle
export type Role = "ADMIN" | "MANAGER" | "RECEPTIONIST";

export const PERMISSIONS = {
  // Lecture seule pour réceptionniste sur chambres et factures
  chambres_write: ["ADMIN", "MANAGER"] as Role[],
  factures_write: ["ADMIN", "MANAGER"] as Role[],
  rapports_view: ["ADMIN", "MANAGER"] as Role[],
  utilisateurs_manage: ["ADMIN"] as Role[],
  parametres_manage: ["ADMIN"] as Role[],
};

export function canAccess(role: string | undefined, allowed: Role[]): boolean {
  if (!role) return false;
  return allowed.includes(role as Role);
}

// Statut chambre / réservation - libellés français
export const STATUT_CHAMBRE_LABELS: Record<string, string> = {
  DISPONIBLE: "Disponible",
  OCCUPEE: "Occupée",
  NETTOYAGE: "Nettoyage",
  MAINTENANCE: "Maintenance",
};

export const STATUT_RESERVATION_LABELS: Record<string, string> = {
  CONFIRMEE: "Confirmée",
  EN_ATTENTE: "En attente",
  ANNULEE: "Annulée",
  TERMINEE: "Terminée",
};

export const TYPE_CHAMBRE_LABELS: Record<string, string> = {
  SIMPLE: "Simple",
  DOUBLE: "Double",
  SUITE: "Suite",
  FAMILIALE: "Familiale",
};

export const METHODE_PAIEMENT_LABELS: Record<string, string> = {
  ESPECES: "Espèces",
  CARTE: "Carte bancaire",
  VIREMENT: "Virement",
  MOBILE_MONEY: "Mobile Money",
};

export const ROLE_LABELS: Record<string, string> = {
  ADMIN: "Administrateur",
  MANAGER: "Manager",
  RECEPTIONIST: "Réceptionniste",
};
