import React, {memo, useEffect, useMemo} from 'react';
import {StyleProp, TextStyle} from 'react-native';
import {useTranslation} from 'react-i18next';
import {useFormContext, useWatch} from 'react-hook-form';
import {HtmlRender} from '@components/_custom';
import {InputRichTextAreaController} from '@components/_HuGo';
import {FormValue} from '@components/DynamicForm';
import {useTheme} from '@shared/theme';

interface Props {
  disabled?: boolean;
  initialValue?: string;
  name: string;
  onChangeInput?: (value: FormValue) => void;
}

function FormTextInput({disabled, initialValue, name, onChangeInput}: Props) {
  const {t} = useTranslation();
  const {theme} = useTheme();
  const {control, setValue} = useFormContext();

  const inputText = useWatch({
    control,
    name,
  });

  useEffect(() => {
    if (inputText) {
      setValue(`${name}-comment`, inputText);
      // Comments in TEXT-type questions should not be required.
      // A temporary handler is added to fix this issue.
      // TODO: Remove this workaround once a proper solution is defined with the squad.
      onChangeInput?.(inputText);
    }
  }, [inputText, name, setValue, onChangeInput]);

  useEffect(() => {
    initialValue !== undefined && setValue(name, initialValue);
  }, [initialValue, name, setValue]);

  const textStyle: StyleProp<TextStyle> = useMemo(
    () => ({color: theme.text.neutral.default}),
    [theme.text.neutral.default],
  );

  return disabled ? (
    <HtmlRender html={initialValue || ''} textStyle={textStyle} />
  ) : (
    <InputRichTextAreaController
      name={name}
      placeholder={t('general.your_answer')}
      disabled={disabled}
    />
  );
}

export default memo(FormTextInput);
