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

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

// Format currency to IDR
export function formatRupiah(amount: number | string | null | undefined): string {
  if (!amount) return 'Rp 0'
  const num = typeof amount === 'string' ? parseFloat(amount) : amount
  return new Intl.NumberFormat('id-ID', {
    style: 'currency',
    currency: 'IDR',
    minimumFractionDigits: 0,
    maximumFractionDigits: 0,
  }).format(num)
}

// Format date to Indonesian
export function formatDate(date: Date | string): string {
  return new Date(date).toLocaleDateString('id-ID', {
    day: 'numeric',
    month: 'long',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  })
}

// Get order status badge config
export function getOrderStatusConfig(status: string) {
  const configs: Record<string, { label: string; color: string; bg: string }> = {
    PENDING: { label: 'Menunggu', color: '#f59e0b', bg: 'rgba(245,158,11,0.15)' },
    PAID: { label: 'Dibayar', color: '#3b82f6', bg: 'rgba(59,130,246,0.15)' },
    PROCESSING: { label: 'Diproses', color: '#8b5cf6', bg: 'rgba(139,92,246,0.15)' },
    SUCCESS: { label: 'Sukses', color: '#10b981', bg: 'rgba(16,185,129,0.15)' },
    FAILED: { label: 'Gagal', color: '#ef4444', bg: 'rgba(239,68,68,0.15)' },
    REFUNDED: { label: 'Refund', color: '#06b6d4', bg: 'rgba(6,182,212,0.15)' },
    CANCELLED: { label: 'Dibatalkan', color: '#6b7280', bg: 'rgba(107,114,128,0.15)' },
  }
  return configs[status] || { label: status, color: '#6b7280', bg: 'rgba(107,114,128,0.15)' }
}

// Generate random string
export function generateId(length = 8): string {
  return Math.random().toString(36).substring(2, 2 + length).toUpperCase()
}

// Mask sensitive data
export function maskEmail(email: string): string {
  const [local, domain] = email.split('@')
  const masked = local.slice(0, 2) + '***' + local.slice(-1)
  return `${masked}@${domain}`
}

export function maskPassword(password: string): string {
  return '•'.repeat(Math.min(password.length, 12))
}

// Calculate sell price with margin
export function calculateSellPrice(basePrice: number, marginPercent: number): number {
  return Math.ceil(basePrice * (1 + marginPercent / 100))
}

// Slug generator
export function slugify(str: string): string {
  return str
    .toLowerCase()
    .replace(/[^a-z0-9\s-]/g, '')
    .replace(/\s+/g, '-')
    .replace(/-+/g, '-')
    .trim()
}
