import {
  FormHelperText,
  Stack,
  Typography,
  useFormControl,
  useTheme,
} from '@mui/material';
import { IconCheck, IconExclamationCircle } from '@tabler/icons-react';

import { type CustomHelperTextProps } from './types';
import {
  getCounterColor,
  getCounterValue,
  getHelperColor,
  shouldShowHelperText,
} from './utils';

const CustomHelperText = ({
  helperText,
  hasCounter,
  maxLength,
  value,
  success,
  error: errorProp,
}: CustomHelperTextProps) => {
  const { error, disabled } = useFormControl() || { error: errorProp };
  const theme = useTheme();

  const helperTextToShow =
    typeof helperText === 'function' ? helperText(value as string) : helperText;

  const showHelperText = shouldShowHelperText(
    hasCounter,
    helperTextToShow,
    error,
  );
  const helperColor = getHelperColor(theme, error, success, disabled);
  const counterColor = getCounterColor(theme, error, success);
  const counterValue = getCounterValue(value, maxLength);

  if (!showHelperText) return null;

  return (
    <FormHelperText
      sx={{
        mx: 0,
        mt: 0.5,
        '& *': {
          color: `${helperColor} !important`,
        },
      }}
    >
      <Stack
        component="span"
        sx={{
          alignItems: 'flex-start',
          flexDirection: 'row',
          gap: 0.5,
          '& > svg': {
            minWidth: '16px',
            height: '22px',
          },
        }}
      >
        {helperTextToShow && (
          <>
            {error && <IconExclamationCircle size="1rem" />}
            {success && <IconCheck size="1rem" />}
            <Typography
              variant="globalS"
              sx={{ flex: 1 }}
            >
              {helperTextToShow}
            </Typography>
          </>
        )}
        {hasCounter && (
          <Typography
            variant="globalS"
            sx={{
              ml: 'auto',
              color: `${counterColor} !important`,
            }}
          >
            {counterValue}
          </Typography>
        )}
      </Stack>
    </FormHelperText>
  );
};

export default CustomHelperText;
