import React, {useEffect, useMemo} from 'react';
import {StyleProp, TextStyle, View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {useFormContext, useWatch} from 'react-hook-form';
import {InputRichTextAreaController, Typography, HtmlRender} from '@components';
import {FormCommentableType} from '@components/DynamicForm/interfaces';
import {useTheme} from '@shared/theme';

interface Props {
  disabled?: boolean;
  initialValue?: string;
  name: string;
  type: FormCommentableType;
  onCommentChange?: (comment: string) => void;
}

function FormComment({
  disabled,
  initialValue,
  name,
  type,
  onCommentChange,
}: Props) {
  const {t} = useTranslation();
  const {theme} = useTheme();

  const {setValue, control} = useFormContext();
  const inputText = useWatch({
    control,
    name: `${name}-comment`,
  });

  useEffect(() => {
    initialValue && setValue(`${name}-comment`, initialValue);
  }, [initialValue, name, setValue]);

  useEffect(() => {
    if (inputText) {
      onCommentChange?.(inputText);
    }
  }, [inputText, name, onCommentChange]);

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

  return disabled ? (
    <View>
      <Typography variant="m">{t('general.comment_one')}</Typography>
      <HtmlRender html={initialValue || ''} textStyle={textStyle} />
    </View>
  ) : (
    <InputRichTextAreaController
      name={`${name}-comment`}
      placeholder={t('general.your_answer')}
      disabled={disabled}
      helper={
        type !== FormCommentableType.REQUIRED ? t('general.optional') : ''
      }
      label={t('general.write_comment')}
    />
  );
}

export default FormComment;
