'use client'

import React, { type ReactElement, useMemo, useState, type ChangeEvent } from 'react'
import Label from '@/Components/Inputs/Label'
import Description from '@/Components/Inputs/Description'
import { type ITextAreaProps } from '@/Types'
import { makeClassName } from '@/utils'
import { Textarea as ShadTextArea } from '@/Components/ui/textarea'

export default function TextArea({
  id,
  testId = 'textarea',
  value,
  onChange,
  error,
  size = 'med',
  defaultClassName = 'block  border border-slate-300 focus:outline-blue-400 w-full disabled:opacity-50 disabled:bg-slate-50',
  disabled = false,
  className,
  defaultWrapperClassName = 'block',
  wrapperClassName,
  placeholder,
  label,
  description,
  before,
  after,
  cleaner,
  autofocus
}: ITextAreaProps): ReactElement {
  const [v, setV] = useState<string | number | undefined>(value)
  const updateValue = (newValue?: string | number): void => {
    setV(newValue)
    value = newValue
  }
  useMemo(() => {
    updateValue(value)
  }, [value])
  const onInputChange = (e: ChangeEvent<HTMLTextAreaElement>): void => {
    let newV = e.target.value
    if (typeof cleaner === 'function') {
      newV = cleaner(newV)
    }
    updateValue(newV)
    if (typeof onChange === 'function') {
      onChange(newV)
    }
  }

  return (
    <label className={makeClassName({
      defaultClassName: defaultWrapperClassName,
      className: wrapperClassName
    })}>
      {
        typeof label === 'string'
          ? <Label label={label} disabled={disabled} />
          : label !== undefined ? label : ''
      }
      {
        typeof description === 'string'
          ? <Description description={description} disabled={disabled} />
          : description !== undefined ? description : ''
      }
      {before !== undefined ? before : ''}
      {error !== undefined ? <p className="text-rose-800 text-xs">{error}</p> : ''}
      <ShadTextArea
        autoFocus={autofocus ?? false}
        data-testid={testId}
        className={makeClassName({
          size,
          defaultClassName,
          className,
          extras: [
            disabled ? 'cursor-not-allowed' : undefined
          ],
          error
        })}
        disabled={disabled}
        placeholder={placeholder}
        onChange={onInputChange}
        value={v !== undefined ? v : ''}

      />
      {after !== undefined ? after : ''}
    </label>
  )
}
