/**
 * Dynamic Textarea Control Component
 *
 * TextareaControl with integrated dynamic variables button.
 *
 * @package
 * @since   1.0.0
 */

import { TextareaControl } from '@wordpress/components';
import { useRef } from '@wordpress/element';
import DynamicVariables from './DynamicVariables';

const DynamicTextareaControl = ({
  label,
  value,
  onChange,
  help,
  placeholder,
  rows = 4,
  context = 'post',
  disabled = false,
  showVariables = true,
  ...props
}) => {
  const textareaRef = useRef();

  const handleInsertVariable = (variable) => {
    // Get the textarea element
    const textarea = textareaRef.current?.querySelector('textarea');
    if (!textarea) {
      // If no cursor position, append to end
      onChange(value + variable);
      return;
    }

    // Get cursor position
    const start = textarea.selectionStart;
    const end = textarea.selectionEnd;

    // Insert variable at cursor position
    const newValue = value.substring(0, start) + variable + value.substring(end);
    onChange(newValue);

    // Set cursor position after the inserted variable
    setTimeout(() => {
      const newPosition = start + variable.length;
      textarea.setSelectionRange(newPosition, newPosition);
      textarea.focus();
    }, 0);
  };

  return (
    <div className="prorank-dynamic-textarea-control" ref={textareaRef}>
      <div className="prorank-dynamic-textarea-control__wrapper">
        <TextareaControl
          label={
            <span className="prorank-dynamic-textarea-control__label">
              {label}
              {showVariables && !disabled && (
                <DynamicVariables
                  onInsert={handleInsertVariable}
                  context={context}
                  disabled={disabled}
                />
              )}
            </span>
          }
          value={value}
          onChange={onChange}
          help={help}
          placeholder={placeholder}
          rows={rows}
          disabled={disabled}
          {...props}
        />
      </div>
    </div>
  );
};

export default DynamicTextareaControl;
