import { type ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge";
import { format, formatDistance } from "date-fns";
import { fr } from "date-fns/locale";

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}

// ─── Formatage monétaire ──────────────────────────────────────
export function formatCurrency(
  amount: number | string,
  currency = "XOF",
  locale = "fr-FR"
): string {
  const num = typeof amount === "string" ? parseFloat(amount) : amount;
  if (currency === "XOF" || currency === "XAF") {
    return new Intl.NumberFormat(locale, {
      style: "decimal",
      minimumFractionDigits: 0,
      maximumFractionDigits: 0,
    }).format(num) + " F CFA";
  }
  return new Intl.NumberFormat(locale, {
    style: "currency",
    currency,
    minimumFractionDigits: 2,
  }).format(num);
}

// ─── Formatage dates ──────────────────────────────────────────
export function formatDate(date: Date | string, pattern = "dd/MM/yyyy"): string {
  return format(new Date(date), pattern, { locale: fr });
}

export function formatDateRelative(date: Date | string): string {
  return formatDistance(new Date(date), new Date(), { addSuffix: true, locale: fr });
}

export function formatDateLong(date: Date | string): string {
  return format(new Date(date), "d MMMM yyyy", { locale: fr });
}

// ─── Pourcentages ─────────────────────────────────────────────
export function formatPercent(value: number): string {
  return new Intl.NumberFormat("fr-FR", {
    style: "percent",
    minimumFractionDigits: 1,
    maximumFractionDigits: 1,
  }).format(value / 100);
}

// ─── Slugify ──────────────────────────────────────────────────
export function slugify(text: string): string {
  return text
    .toLowerCase()
    .normalize("NFD")
    .replace(/[̀-ͯ]/g, "")
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "");
}

// ─── Numéros de facture ───────────────────────────────────────
export function generateInvoiceNumber(prefix: string, counter: number): string {
  const year = new Date().getFullYear();
  const padded = String(counter + 1).padStart(4, "0");
  return `${prefix}-${year}-${padded}`;
}

// ─── Calculs TVA ──────────────────────────────────────────────
export function calculateTax(amount: number, taxRate: number): number {
  return Math.round(amount * (taxRate / 100) * 100) / 100;
}

export function calculateTotal(subtotal: number, taxAmount: number, discount = 0): number {
  return subtotal + taxAmount - discount;
}

// ─── Troncature texte ────────────────────────────────────────
export function truncate(text: string, maxLength: number): string {
  if (text.length <= maxLength) return text;
  return text.slice(0, maxLength) + "…";
}

// ─── Initiales avatar ─────────────────────────────────────────
export function getInitials(name: string): string {
  return name
    .split(" ")
    .map((n) => n[0])
    .join("")
    .toUpperCase()
    .slice(0, 2);
}

// ─── Couleur statut facture ───────────────────────────────────
export const INVOICE_STATUS_CONFIG = {
  DRAFT:     { label: "Brouillon",   color: "bg-gray-100 text-gray-700",   dot: "bg-gray-400"  },
  SENT:      { label: "Envoyée",     color: "bg-blue-100 text-blue-700",   dot: "bg-blue-500"  },
  PAID:      { label: "Payée",       color: "bg-green-100 text-green-700", dot: "bg-green-500" },
  OVERDUE:   { label: "En retard",   color: "bg-red-100 text-red-700",     dot: "bg-red-500"   },
  CANCELED:  { label: "Annulée",     color: "bg-gray-100 text-gray-500",   dot: "bg-gray-400"  },
  REFUNDED:  { label: "Remboursée",  color: "bg-orange-100 text-orange-700", dot: "bg-orange-500" },
} as const;

export const EXPENSE_STATUS_CONFIG = {
  PENDING:    { label: "En attente",   color: "bg-yellow-100 text-yellow-700" },
  APPROVED:   { label: "Approuvée",    color: "bg-green-100 text-green-700"  },
  REJECTED:   { label: "Refusée",      color: "bg-red-100 text-red-700"      },
  REIMBURSED: { label: "Remboursée",   color: "bg-blue-100 text-blue-700"    },
} as const;

// ─── Limites par plan ─────────────────────────────────────────
export const PLAN_LIMITS = {
  FREE:     { invoices: 10, expenses: 50, users: 1,  bankAccounts: 1,  storage: 100 },
  PRO:      { invoices: 100, expenses: 500, users: 5, bankAccounts: 3,  storage: 5000 },
  BUSINESS: { invoices: -1, expenses: -1, users: -1, bankAccounts: -1, storage: -1 },
} as const;
