'use client'

import React from 'react'

export interface TextareaProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {
  label?: string
  error?: string
  helperText?: string
  fullWidth?: boolean
}

export const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
  (
    {
      label,
      error,
      helperText,
      fullWidth = false,
      className = '',
      id,
      required,
      disabled,
      rows = 4,
      ...props
    },
    ref
  ) => {
    const textareaId = id || `textarea-${Math.random().toString(36).substr(2, 9)}`
    const errorId = `${textareaId}-error`
    const helperId = `${textareaId}-helper`

    const hasError = Boolean(error)

    const baseStyles = 'block w-full rounded-md border transition-colors duration-150 focus:outline-none focus:ring-2 focus:ring-offset-0 px-4 py-2'
    const normalStyles = 'border-gray-300 focus:border-primary-500 focus:ring-primary-500 dark:border-gray-600 dark:bg-gray-800 dark:text-white'
    const errorStyles = 'border-error-500 focus:border-error-500 focus:ring-error-500'
    const disabledStyles = 'disabled:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-60 dark:disabled:bg-gray-900'

    const textareaClassName = `${baseStyles} ${hasError ? errorStyles : normalStyles} ${disabledStyles} ${className}`.trim()
    const containerWidth = fullWidth ? 'w-full' : ''

    return (
      <div className={containerWidth}>
        {label && (
          <label
            htmlFor={textareaId}
            className="block text-sm font-medium text-gray-700 dark:text-gray-200 mb-1"
          >
            {label}
            {required && <span className="text-error-500 ml-1" aria-label="required">*</span>}
          </label>
        )}

        <textarea
          ref={ref}
          id={textareaId}
          className={textareaClassName}
          aria-invalid={hasError}
          aria-describedby={
            hasError ? errorId : helperText ? helperId : undefined
          }
          required={required}
          disabled={disabled}
          rows={rows}
          {...props}
        />

        {error && (
          <p className="mt-1 text-sm text-error-500" id={errorId} role="alert">
            {error}
          </p>
        )}

        {helperText && !error && (
          <p className="mt-1 text-sm text-gray-500 dark:text-gray-400" id={helperId}>
            {helperText}
          </p>
        )}
      </div>
    )
  }
)

Textarea.displayName = 'Textarea'
