"use client";

import * as React from "react";

import {
  InputGroup,
  InputGroupAddon,
  InputGroupInput,
  InputGroupText,
} from "@/components/ui/input-group";
import { useTranslation } from "@/hooks/useTranslation";
import { cn } from "@/lib/utils";

interface CurrencyInputProps extends Omit<
  React.ComponentProps<"input">,
  "value" | "onChange" | "type" | "inputMode" | "dir"
> {
  /**
   * Sanitized decimal string, e.g. "125" / "125.5" / "" when unset.
   * Kept as a string so intermediate typing states ("125.") survive —
   * coerce to number in the zod schema (`z.coerce.number()`).
   */
  value?: string;
  onChange?: (value: string) => void;
  /** Extra classes for the outer InputGroup */
  className?: string;
}

/** Keep digits + a single decimal point with at most 2 decimals */
function sanitizeAmount(raw: string): string {
  let cleaned = raw.replace(/[^\d.]/g, "");
  const firstDot = cleaned.indexOf(".");
  if (firstDot !== -1) {
    const whole = cleaned.slice(0, firstDot);
    const decimals = cleaned
      .slice(firstDot + 1)
      .replace(/\./g, "")
      .slice(0, 2);
    cleaned = `${whole}.${decimals}`;
  }
  return cleaned;
}

/**
 * SAR amount input (pricing, refunds, platform fee settings).
 *
 * - Digits + up to 2 decimals only; value contract is a sanitized string.
 * - Prices are compound LTR content (design RTL rule 5) — the whole group is
 *   forced `dir="ltr"` and the digits render in the numeric (Inter) font.
 * - The currency label comes from the dictionary ("SAR" / "ر.س").
 */
function CurrencyInput({
  value = "",
  onChange,
  className,
  ...props
}: CurrencyInputProps) {
  const { t } = useTranslation();

  function handleChange(event: React.ChangeEvent<HTMLInputElement>) {
    onChange?.(sanitizeAmount(event.target.value));
  }

  return (
    <InputGroup dir="ltr" className={cn(className)}>
      <InputGroupInput
        inputMode="decimal"
        autoComplete="off"
        className="font-numeric"
        value={value}
        onChange={handleChange}
        {...props}
      />
      <InputGroupAddon align="inline-end">
        <InputGroupText className="text-main-text">
          {t("common.currencySAR")}
        </InputGroupText>
      </InputGroupAddon>
    </InputGroup>
  );
}

export { CurrencyInput };
