import { forwardRef } from 'react';

import { IconX } from '@material-hu/icons/tabler';
import FormControl from '@material-hu/mui/FormControl';
import IconButton from '@material-hu/mui/IconButton';
import Stack from '@material-hu/mui/Stack';
import { composeSx } from '@material-hu/utils/components';

import CustomHelperText from '@material-hu/components/design-system/Inputs/Base/CustomHelperText';

import { EditableArea, Placeholder } from './styles';
import {
  type CertificateMultilineHandle,
  type CertificateMultilineWithTokenHighlightProps,
} from './types';
import { useTokenEditor } from './useTokenEditor';

const CertificateMultilineWithTokenHighlight = forwardRef<
  CertificateMultilineHandle,
  CertificateMultilineWithTokenHighlightProps
>(
  (
    {
      name,
      rules,
      maxLength,
      minRows,
      maxRows,
      id,
      placeholder,
      showClear = true,
      hasCounter = true,
      sx,
    },
    ref,
  ) => {
    const {
      assignRef,
      strValue,
      counterValue,
      disabled,
      error,
      errorMessage,
      showClearButton,
      containerSx,
      clearLabel,
      handlers,
    } = useTokenEditor({ name, rules, maxLength, showClear }, ref);

    return (
      <FormControl
        fullWidth
        error={error}
        disabled={disabled}
        sx={composeSx({ width: '100%', minWidth: 0, alignSelf: 'stretch' }, sx)}
      >
        <Stack sx={containerSx}>
          <EditableArea
            ref={assignRef}
            id={id}
            role="textbox"
            aria-multiline
            aria-invalid={error}
            contentEditable={!disabled}
            suppressContentEditableWarning
            onInput={handlers.onInput}
            onKeyDown={handlers.onKeyDown}
            onPaste={handlers.onPaste}
            onFocus={handlers.onFocus}
            onBlur={handlers.onBlur}
            ownerState={{
              disabled,
              showClear,
              minRows,
              maxRows,
            }}
          />
          {!strValue && <Placeholder aria-hidden>{placeholder}</Placeholder>}
          {showClearButton && (
            <IconButton
              aria-label={clearLabel}
              size="small"
              onMouseDown={e => {
                e.preventDefault();
                handlers.onClear();
              }}
              sx={{ position: 'absolute', top: 8, right: 8 }}
            >
              <IconX size={20} />
            </IconButton>
          )}
        </Stack>
        <CustomHelperText
          helperText={errorMessage}
          hasCounter={hasCounter}
          maxLength={maxLength}
          value={counterValue}
          error={error}
        />
      </FormControl>
    );
  },
);

CertificateMultilineWithTokenHighlight.displayName =
  'CertificateMultilineWithTokenHighlight';

export type { CertificateMultilineHandle } from './types';

export default CertificateMultilineWithTokenHighlight;
