import { useController, useFormContext } from 'react-hook-form';

import { buttonClasses } from '@material-hu/mui/Button';
import FormControl from '@material-hu/mui/FormControl';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import HuButtonGroup from '@material-hu/components/design-system/ButtonGroup';

type ScaleFieldProps = {
  name: string;
  labels: string[];
  subLabels?: string[];
  helperTextElement?: React.ReactNode;
};

const ScaleField = ({
  name,
  labels,
  subLabels,
  helperTextElement,
}: ScaleFieldProps) => {
  const { control } = useFormContext();

  const {
    field: { onChange, value },
  } = useController({
    name,
    control,
    defaultValue: null,
  });

  return (
    <FormControl
      sx={{
        [`.${buttonClasses.root}`]: {
          height: 'auto',
        },
      }}
    >
      <HuButtonGroup
        labels={labels}
        showCheckIcon={false}
        onChange={onChange}
        value={value}
        fullWidth
      />
      {subLabels?.length && (
        <Stack sx={{ flexDirection: 'row' }}>
          {subLabels.map((subLabel, index) => (
            <Typography
              key={index}
              sx={{
                flex: 1,
                textAlign: 'center',
                color: theme => theme.palette.new.text.neutral.disabled,
                py: 0.5,
              }}
              variant="globalXXS"
            >
              {subLabel}
            </Typography>
          ))}
        </Stack>
      )}
      {helperTextElement}
    </FormControl>
  );
};

export default ScaleField;
