import { type VariantProps } from 'class-variance-authority';

import * as React from 'react';

import { cn } from '@/lib/utils';

import { inputVariants } from './input-variants';

export interface TextareaProps
  extends React.TextareaHTMLAttributes<HTMLTextAreaElement>,
    VariantProps<typeof inputVariants> {
  showCharacterCount?: boolean;
}

const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
  ({ className, showCharacterCount = false, maxLength, value, variant, fieldSize, ...props }, ref) => {
    const currentLength = typeof value === 'string' ? value.length : 0;
    const showCount = showCharacterCount && maxLength != null;

    const textareaEl = (
      <textarea
        className={cn(
          inputVariants({ variant, fieldSize }),
          'min-h-[80px]',
          className,
        )}
        ref={ref}
        maxLength={maxLength}
        value={value}
        {...props}
      />
    );

    if (showCount) {
      return (
        <div className="w-full">
          {textareaEl}
          <p className="text-xs text-muted-foreground mt-1">
            {currentLength} / {maxLength} characters
          </p>
        </div>
      );
    }

    return textareaEl;
  },
);
Textarea.displayName = 'Textarea';

export { Textarea };
