import React, { useState } from 'react';
import { Input } from '@/components/ui/input';
import { parseCurrency, formatCurrency, formatCurrencyForInput } from '../utils/dateUtils';

/**
 * CurrencyInputV2 component for robust currency handling.
 * Displays formatted currency (R$ 0,00) when blurred.
 * Displays raw numeric format (0,00) when focused for easier editing.
 * 
 * @param {Object} props - Component props
 * @param {number|string} props.value - Numeric value
 * @param {Function} props.onChange - Callback with the numeric value
 * @param {string} [props.placeholder] - Input placeholder
 * @param {string} [props.className] - Additional CSS classes
 */
export const CurrencyInputV2 = ({ value, onChange, placeholder = "R$ 0,00", className, ...props }) => {
  const [focused, setFocused] = useState(false);
  const [localValue, setLocalValue] = useState('');

  const isEmpty = value === '' || value == null;
  const displayValue = focused ? localValue : (isEmpty ? '' : formatCurrency(value));

  const handleFocus = () => {
    setFocused(true);
    setLocalValue(isEmpty ? '' : formatCurrencyForInput(value));
  };

  const handleBlur = () => {
    const numericValue = parseCurrency(localValue);
    onChange(numericValue === '' ? '' : numericValue);
    setFocused(false);
  };

  return (
    <Input
      {...props}
      type="text"
      inputMode="decimal"
      className={className}
      placeholder={placeholder}
      value={displayValue}
      onFocus={handleFocus}
      onBlur={handleBlur}
      onChange={(e) => setLocalValue(e.target.value)}
    />
  );
};
