import { forwardRef, useCallback, useRef } from 'react'
import { useAutoResizeTextarea } from './useAutoResizeTextarea'

export interface ChatInputTextareaProps extends Omit<React.TextareaHTMLAttributes<HTMLTextAreaElement>, 'value' | 'onChange'> {
  value: string
  onChange?: (value: string) => void
  placeholder?: string
  disabled?: boolean
  maxRows?: number
  onKeyDown?: (e: React.KeyboardEvent<HTMLTextAreaElement>) => void
}

export const ChatInputTextarea = forwardRef<HTMLTextAreaElement, ChatInputTextareaProps>(
  (
    {
      value,
      onChange,
      placeholder = 'What can I help you with today?',
      disabled = false,
      maxRows = 6,
      onKeyDown,
      className,
      style,
      ...props
    },
    ref
  ) => {
    const innerRef = useRef<HTMLTextAreaElement>(null)
    useAutoResizeTextarea(innerRef, value, maxRows)

    const setRef = useCallback(
      (node: HTMLTextAreaElement | null) => {
        (innerRef as React.MutableRefObject<HTMLTextAreaElement | null>).current = node
        if (typeof ref === 'function') ref(node)
        else if (ref) (ref as React.MutableRefObject<HTMLTextAreaElement | null>).current = node
      },
      [ref]
    )

    const handleChange = useCallback(
      (e: React.ChangeEvent<HTMLTextAreaElement>) => onChange?.(e.target.value),
      [onChange]
    )

    const textareaNoFocusStyle = { outline: 'none', border: 'none', boxShadow: 'none' } as const
    const textareaStyles =
      'w-full resize-none border-none bg-transparent text-sm leading-sm font-normal placeholder:text-text-tertiary overflow-y-auto scrollbar-auto outline-none shadow-none focus:outline-none focus:ring-0 focus:shadow-none focus-visible:outline-none focus-visible:ring-0 focus-visible:shadow-none [&:focus-visible]:outline-none [&:focus-visible]:ring-0 [&:focus-visible]:ring-offset-0 [&:focus-visible]:shadow-none ' +
      (value?.trim() ? 'text-text' : 'text-text-quaternary')

    return (
      <textarea
        ref={setRef}
        value={value}
        onChange={handleChange}
        onKeyDown={onKeyDown}
        placeholder={placeholder}
        disabled={disabled}
        rows={1}
        className={[textareaStyles, className].filter(Boolean).join(' ')}
        {...props}
        style={{ ...(style ?? {}), ...textareaNoFocusStyle }}
      />
    )
  }
)

ChatInputTextarea.displayName = 'ChatInputTextarea'
