import React, { useEffect, useState } from 'react';
import { toEnglishDigits } from '../../lib/utils';

interface PriceInputProps {
  value: number | '';
  onChange: (value: number) => void;
  placeholder?: string;
  className?: string;
  style?: React.CSSProperties;
  disabled?: boolean;
  min?: number;
  /** نمایش ارقام لاتین با جداکنندهٔ کاما (پیش‌فرض: فارسی). */
  latin?: boolean;
}

function formatDisplay(num: number, latin: boolean): string {
  if (num === 0) return '';
  return new Intl.NumberFormat(latin ? 'en-US' : 'fa-IR').format(num);
}

export default function PriceInput({
  value,
  onChange,
  placeholder = '0',
  className,
  style,
  disabled,
  min = 0,
  latin = false,
}: PriceInputProps) {
  const [display, setDisplay] = useState(() => (value !== '' && value > 0 ? formatDisplay(value, latin) : ''));

  useEffect(() => {
    setDisplay(value !== '' && Number(value) > 0 ? formatDisplay(Number(value), latin) : '');
  }, [value, latin]);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const raw = toEnglishDigits(e.target.value).replace(/[^0-9]/g, '');
    const num = raw === '' ? 0 : Math.max(min, parseInt(raw, 10));
    onChange(num);
    setDisplay(num > 0 ? formatDisplay(num, latin) : '');
  };

  return (
    <input
      type="text"
      inputMode="numeric"
      value={display}
      onChange={handleChange}
      placeholder={placeholder}
      className={className}
      style={{ textAlign: 'left', direction: 'ltr', ...style }}
      disabled={disabled}
    />
  );
}
