import { Box, styled, TextField, Typography } from '@mui/material'
import { Controller } from 'react-hook-form'

const StyledInlineTextField = styled(TextField)(({ theme }) => ({
  maxHeight: '35px',
  '& legend': {
    display: 'none',
  },

  '& fieldset': {
    top: 0,
  },
}))

const StyledInlineFlex = styled(Box)(({ theme }) => ({
  width: '100%',
  flexWrap: 'wrap',
  display: 'flex',
  gap: '10px',
  alignItems: 'baseline',
  '& .MuiTypography-root': {
    flexShrink: 0,
  },
  '& .MuiTextField-root': {
    maxWidth: '100px',
  },
}))

export const FormInlineTextField = ({ control, label }) => {
  const regex = /\{([^}]+)\}/
  const splitArr = label.split(regex)

  function getParsedArr(arr) {
    for (let i = 1; i < arr.length; i += 2) {
      const split = arr[i].split(':')
      arr[i] = (
        <Controller
          name={split[0]}
          control={control}
          render={({ field: { onChange, value }, fieldState: { error } }) => (
            <StyledInlineTextField
              size="small"
              key={i}
              placeholder={split[1] ?? ''}
              value={value}
              onChange={onChange}
              error={error ? true : false}
              helperText={error ? error.message : null}
            />
          )}
        />
      )
    }
    return arr
  }

  return (
    <StyledInlineFlex>
      {getParsedArr(splitArr)?.map((item, index) => {
        if (typeof item === 'string' && item.length) {
          return (
            <Typography variant="body1" key={index}>
              {item}
            </Typography>
          )
        }

        return item
      })}
    </StyledInlineFlex>
  )
}

export default FormInlineTextField
