'use client'

import * as React from 'react'
import { cn } from '@/lib/utils/cn'
import { ErrorIcon } from '../icons/form-icon'

export interface TextareaProps extends React.ComponentProps<'textarea'> {
  label?: string
  containerClass?: string
  labelClass?: string
  hasError?: boolean
  errorMessage?: string
}

export function Textarea({
  label,
  containerClass,
  labelClass,
  className,
  hasError = false,
  errorMessage,
  ...props
}: TextareaProps) {
  const textareaId = React.useId()
  const isFilled = props.value != null && String(props.value).length > 0

  return (
    <div className={cn(containerClass)}>
      {label && (
        <label
          htmlFor={textareaId}
          className={cn(
            'block text-grey-50 caption-medium-medium pointer-events-none pb-2',
            labelClass,
          )}
        >
          {label}
        </label>
      )}
      <textarea
        id={textareaId}
        data-slot="textarea"
        {...props}
        className={cn(
          'group font-b2-regular placeholder:text-grey-200 text-base-white hover:placeholder:text-grey-100',
          'w-full min-w-0 rounded-md px-4 py-3 text-base outline-none shadow-xs transition-[background-color,box-shadow] duration-150',
          'bg-neutral-700 focus:bg-neutral-700',
          !isFilled && 'group-hover:bg-neutral-500 hover:bg-neutral-500',
          'min-h-[64px]',
          'disabled:cursor-not-allowed disabled:opacity-50',
          'focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]',
          'aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40',
          hasError ? 'border border-func-red-main' : 'border-[#FCFCFC33]',
          className,
        )}
      />
      {hasError && errorMessage && (
        <div className="flex items-center justify-start mt-2">
          <ErrorIcon width={20} height={20} className="text-func-red-main flex-shrink-0" />
          <p className={cn('label-medium-regular ml-1 text-func-red-main')}>{errorMessage}</p>
        </div>
      )}
    </div>
  )
}
