import { useState, useCallback } from 'react';

export function useCurrencyMask(initialValue = '') {
  const [displayValue, setDisplayValue] = useState(initialValue);
  const [numericValue, setNumericValue] = useState(0);

  const formatCurrency = useCallback((value) => {
    // Remove all non-numeric characters
    const numbers = value.replace(/\D/g, '');
    
    if (!numbers) {
      return '';
    }
    
    // Convert to number (cents)
    const amount = parseInt(numbers, 10);
    
    // Format with thousand separators and decimal
    const formatted = (amount / 100).toFixed(2)
      .replace('.', ',')
      .replace(/\B(?=(\d{3})+(?!\d))/g, '.');
    
    return `R$ ${formatted}`;
  }, []);

  const handleChange = useCallback((e) => {
    const value = e.target.value;
    const formatted = formatCurrency(value);
    setDisplayValue(formatted);
    
    // Extract numeric value
    const numbers = value.replace(/\D/g, '');
    const numeric = numbers ? parseInt(numbers, 10) / 100 : 0;
    setNumericValue(numeric);
  }, [formatCurrency]);

  const setValue = useCallback((value) => {
    const formatted = formatCurrency(String(value * 100));
    setDisplayValue(formatted);
    setNumericValue(value);
  }, [formatCurrency]);

  return {
    displayValue,
    numericValue,
    handleChange,
    setValue
  };
}