import React, { forwardRef } from 'react';
import { Input } from "@chakra-ui/react";

export const formatCurrency = (value) => {
  if (value === undefined || value === null) return ''; 
  const [integer, decimal] = String(value).split('.'); 
  const formattedInteger = integer.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  return decimal !== undefined ? `${formattedInteger}.${decimal}` : formattedInteger;
};
const CurrencyInput = forwardRef(({ value, onChange, ...props }, ref) => {

  const handleChange = (event) => {
    let { value } = event?.target;

    // Remove non-numeric characters except decimal point
    value = value.replace(/[^0-9.]/g, '');

    // Ensure only one decimal point
    const parts = value.split('.');
    if (parts.length > 2) {
      value = parts[0] + '.' + parts.slice(1).join('');
    }

    // Restrict to two decimal places
    if (parts[1]?.length > 2) {
      value = parts[0] + '.' + parts[1].slice(0, 2);
    }

    onChange(value); // Pass the raw value to parent
  };

  return (
    <Input
      {...props}
      ref={ref}  // Forward ref here
      type="text"
      value={formatCurrency(value)}
      onChange={handleChange}
    />
  );
});

export default CurrencyInput;




// import React, { forwardRef } from 'react';
// import { Input } from "@chakra-ui/react";

// export const formatCurrency = (value) => {
//   if (value === undefined || value === null) return ''; // Handle undefined or null values
//   const [integer, decimal] = String(value).split('.'); // Convert value to string before splitting
//   const formattedInteger = integer.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
//   return decimal ? `${formattedInteger}.${decimal}` : formattedInteger;
// };

// const CurrencyInput = forwardRef(({ value, onChange, ...props }, ref) => {

//   const handleChange = (event) => {
//     let { value } = event?.target;

//     // Remove non-numeric characters except decimal point
//     value = value?.replace(/[^0-9.]/g, '');

//     // Ensure only one decimal point and restrict to two decimal places
//     const parts = value?.split('.');
//     if (parts.length > 2) {
//       value = parts[0] + '.' + parts?.slice(1)?.join('');
//     }

//     if (parts[1]?.length > 2) {
//       value = parts[0] + '.' + parts[1]?.slice(0, 2);
//     }

//     onChange(value); // Pass the raw value to parent or use it directly
//   };

//   return (
//     <Input
//       {...props}
//       ref={ref}  // Forward ref here
//       type="text"
//       value={formatCurrency(value)}
//       onChange={handleChange}
//     />
//   );
// });

// export default CurrencyInput;
