import { useTranslation } from 'react-i18next';

import { Box, FormControl, Stack, useTheme } from '@mui/material';
import { EditorContent } from '@tiptap/react';

import CustomHelperText from '../Base/CustomHelperText';
import CustomLabel from '../Base/CustomLabel';
import { getBorderColor } from '../utils';

import InsertVariable from './actions/InsertVariable';
import ActionsBar from './components/ActionsBar';
import { TextAreaReadOnlyView } from './components/TextAreaReadOnlyView';
import { getEditorStyles } from './constants';
import { TextAreaProvider, useTextArea } from './context';
import { type TextAreaProps, type TextAreaWrapperProps } from './types';

const TextAreaWrapper = ({
  label,
  success,
  error,
  errorText,
  helperText,
  sx,
  simplifyEditor,
  actions,
  visibleActions,
}: TextAreaWrapperProps) => {
  const { editor, slotProps } = useTextArea();
  const theme = useTheme();
  const { t } = useTranslation('material_hu_only');

  const disabled = !editor?.isEditable;

  return (
    <FormControl
      sx={{
        width: '100%',
        ...sx,
      }}
      error={error}
      disabled={disabled}
    >
      <CustomLabel
        label={label}
        success={success}
      />
      <Stack
        sx={{
          containerType: 'inline-size',
          position: 'relative',
          ...getEditorStyles(theme),
          border: '1px solid',
          borderRadius: 2,
          borderColor: getBorderColor(
            theme,
            editor?.isFocused,
            error,
            success,
            !editor?.isEmpty,
          ),
          backgroundColor: theme.palette.new.background.elements.default,
          transition: 'border 125ms ease-in-out',
        }}
      >
        {!disabled && (
          <ActionsBar
            simplifyEditor={simplifyEditor}
            actions={actions}
            visibleActions={visibleActions}
          />
        )}
        {editor && (
          <EditorContent
            editor={editor}
            style={
              actions?.insertVariable
                ? { paddingBottom: theme.spacing(5) }
                : undefined
            }
          />
        )}
        {!disabled && actions?.insertVariable && (
          <Box
            sx={{
              position: 'absolute',
              bottom: theme.spacing(1),
              right: theme.spacing(1),
              zIndex: 2,
            }}
          >
            <InsertVariable
              title={t('top_bar_rich_text_editor.insert_variable')}
              variables={slotProps?.insertVariable?.variables ?? []}
            />
          </Box>
        )}
      </Stack>

      <CustomHelperText
        value={editor?.getText() || ''}
        helperText={error ? errorText : helperText}
        success={success}
      />
    </FormControl>
  );
};

const TextArea = ({
  actions,
  simplifyEditor,
  visibleActions,
  content,
  disabled,
  readOnly,
  error,
  errorText,
  handlePaste,
  helperText,
  handleDrop,
  label,
  onChange,
  onBlur,
  onFocus,
  placeholder,
  slotProps,
  success,
  sx,
  immediatelyRender = true,
  characterLimit,
}: TextAreaProps) => {
  return (
    <TextAreaProvider
      onChange={onChange}
      onBlur={onBlur}
      onFocus={onFocus}
      content={content}
      slotProps={slotProps}
      handlePaste={handlePaste}
      handleDrop={handleDrop}
      placeholder={placeholder}
      disabled={disabled}
      readOnly={readOnly}
      immediatelyRender={immediatelyRender}
      variablesEnabled={!!actions?.insertVariable}
      characterLimit={characterLimit}
    >
      {readOnly ? (
        <TextAreaReadOnlyView sx={sx} />
      ) : (
        <TextAreaWrapper
          error={error}
          errorText={errorText}
          helperText={helperText}
          label={label}
          success={success}
          sx={sx}
          simplifyEditor={simplifyEditor}
          actions={actions}
          visibleActions={visibleActions}
        />
      )}
    </TextAreaProvider>
  );
};

export type { ActionId, TextAreaProps } from './types';
export type {
  InsertVariableProps,
  VariableNode,
  VariableNodeInput,
  LegacyVariableNode,
} from './actions/InsertVariable/types';
export {
  buildTokenLabelMap,
  normalizeVariables,
  prepareForBackend,
  prepareForEditor,
} from './utils/variableSerialization';

export default TextArea;
