import React from 'react';
import InputAdornment from '@mui/material/InputAdornment';
import TextField from '@mui/material/TextField';
import { formatCurrency, parseCurrency } from '@laboratoria/sdk-js';

const CurrencyTextField = ({
  label,
  required,
  value,
  error,
  helperText,
  currencySymbol,
  currencyCode,
  currencyName,
  countryCode,
  onChange,
  lang = 'es',
}) => {
  const printableValue = (
    typeof value === 'undefined'
      ? ''
      : formatCurrency(value, lang, countryCode, currencyCode)
  );

  return (
    <TextField
      label={label}
      required={required}
      value={printableValue}
      error={!!error}
      helperText={helperText}
      InputProps={{
        startAdornment: (
          <InputAdornment position="start">
            {currencySymbol}
          </InputAdornment>
        ),
        endAdornment: (
          <InputAdornment position="end">
            {`${currencyCode} ${currencyName}`}
          </InputAdornment>
        ),
      }}
      onChange={(e) => {
        if (e.target.value === '') {
          return onChange(undefined);
        }

        const newVal = parseCurrency(e.target.value);
        return onChange(newVal);
      }}
    />
  );
};

export default CurrencyTextField;