"use client";

import * as React from "react";
import { Input } from "@/components/ui/input";
import { cn } from "@/lib/utils";

/**
 * Money input for Toman amounts: shows grouped thousands separators while the
 * user types (e.g. 1490000 → 1,490,000) but reports a raw digit string via
 * onValueChange so callers keep parsing with Number()/parseFloat() unchanged.
 * Accepts Persian/Arabic digits on input and normalizes them to Latin.
 */
export type MoneyInputProps = Omit<
  React.ComponentProps<typeof Input>,
  "value" | "onChange" | "inputMode" | "type"
> & {
  /** Raw digit string, e.g. "1490000" (no separators). */
  value: string;
  /** Called with the normalized raw digit string. */
  onValueChange: (rawDigits: string) => void;
};

const PERSIAN_DIGITS = "۰۱۲۳۴۵۶۷۸۹";
const ARABIC_DIGITS = "٠١٢٣٤٥٦٧٨٩";

function toRawDigits(input: string): string {
  let out = "";
  for (const ch of input) {
    const fa = PERSIAN_DIGITS.indexOf(ch);
    const ar = ARABIC_DIGITS.indexOf(ch);
    if (ch >= "0" && ch <= "9") out += ch;
    else if (fa !== -1) out += String(fa);
    else if (ar !== -1) out += String(ar);
    // ignore separators, spaces, and anything else
  }
  // strip leading zeros but keep a single "0"
  out = out.replace(/^0+(?=\d)/, "");
  return out;
}

function group(raw: string): string {
  if (!raw) return "";
  return Number(raw).toLocaleString("en-US");
}

export const MoneyInput = React.forwardRef<HTMLInputElement, MoneyInputProps>(
  ({ value, onValueChange, className, ...props }, ref) => {
    return (
      <Input
        ref={ref}
        value={group(value)}
        onChange={(e) => onValueChange(toRawDigits(e.target.value))}
        inputMode="numeric"
        dir="ltr"
        className={cn("text-end tabular-nums", className)}
        {...props}
      />
    );
  }
);
MoneyInput.displayName = "MoneyInput";
