import { AedSymbol } from "./aed-symbol"
import { cn } from "@/shared/lib/utils"

type MoneyProps = {
    value?: number | string | null
    /** Prepended before the symbol (e.g. "–" or "+"). */
    prefix?: string
    /** Hide the AED symbol — useful when the column header already conveys currency. */
    hideSymbol?: boolean
    /** Locale override for number grouping. */
    locale?: string
    /** Minimum/maximum fraction digits. Defaults to 2. */
    fractionDigits?: number
    /** Fallback rendered when value is null/undefined/NaN. */
    fallback?: string
    className?: string
}

function formatAmount(value: number | string | null | undefined, locale: string | undefined, digits: number): string | null {
    if (value == null || value === "") return null
    const num = typeof value === "string" ? Number(value) : value
    if (Number.isNaN(num)) return null
    return new Intl.NumberFormat(locale, {
        minimumFractionDigits: digits,
        maximumFractionDigits: digits,
    }).format(num)
}

export function Money({
    value,
    prefix,
    hideSymbol = false,
    locale,
    fractionDigits = 2,
    fallback = "—",
    className,
}: MoneyProps) {
    const formatted = formatAmount(value, locale, fractionDigits)
    if (formatted == null) return <span className={className}>{fallback}</span>

    return (
        <span className={cn("inline-flex items-center gap-[0.2em] whitespace-nowrap", className)}>
            {prefix ? <span>{prefix}</span> : null}
            {!hideSymbol ? <AedSymbol /> : null}
            <span>{formatted}</span>
        </span>
    )
}
