import { type FC } from 'react';
import { Controller } from 'react-hook-form';

import { type EditorOptions } from '@tiptap/react';

import { type FormTextAreaProps } from './types';
import TextArea from '.';

const FormTextArea: FC<FormTextAreaProps> = ({
  name,
  textAreaProps = {},
  rules,
}) => {
  return (
    <Controller
      name={name}
      rules={rules}
      render={({
        field: { onChange, value, ref, onBlur: fieldOnBlur, ...field },
        fieldState: { error },
      }) => {
        const showError = !!error;

        return (
          <TextArea
            {...textAreaProps}
            {...field}
            content={value}
            onChange={onChange}
            onBlur={(...args: Parameters<EditorOptions['onBlur']>) => {
              fieldOnBlur(); // marks touched
              textAreaProps.onBlur?.(...args);
            }}
            error={showError}
            errorText={
              showError ? textAreaProps?.errorText || error?.message : undefined
            }
          />
        );
      }}
    />
  );
};

export type { FormTextAreaProps };

export default FormTextArea;
