import React from 'react';
import {
  Textarea as ChakraTextarea,
  FormControl,
  FormLabel,
  FormErrorMessage,
  FormHelperText,
  useColorModeValue,
} from '@chakra-ui/react';


export interface TextAreaProps {
  /**
   * Label for the textarea
   */
  label?: string;

  /**
   * Error message to display
   */
  error?: string;

  /**
   * Helper text to display below the textarea
   */
  helperText?: string;

  /**
   * Size of the textarea
   */
  size?: 'sm' | 'md' | 'lg';

  /**
   * Whether the textarea is required
   */
  isRequired?: boolean;

  /**
   * Maximum number of rows before scrolling
   */
  maxRows?: number;

  /**
   * Minimum number of rows
   */
  minRows?: number;

  /**
   * Whether to auto-resize based on content
   */
  isResizable?: boolean;

  /**
   * ID for the textarea input
   */
  id?: string;

  /**
   * Placeholder text
   */
  placeholder?: string;
}

/**
 * TextArea component using Chakra UI's Textarea with BFUI theme customizations
 */
export const TextArea: React.FC<TextAreaProps> = ({
  label,
  error,
  helperText,
  size = 'md',
  isRequired = false,
  maxRows,
  minRows = 3,
  isResizable = true,
  id,
  placeholder,
  ...rest
}) => {
  const inputId = id || label?.toLowerCase().replace(/\s+/g, '-');
  const bg = useColorModeValue('white', 'gray.800');
  const borderColor = useColorModeValue('gray.200', 'gray.600');

  // Calculate rows based on minRows and maxRows
  const rows = maxRows ? Math.min(Math.max(minRows, maxRows), maxRows) : minRows;

  return (
    <FormControl isInvalid={!!error} isRequired={isRequired}>
      {label && <FormLabel htmlFor={inputId}>{label}</FormLabel>}
      <ChakraTextarea
        id={inputId}
        size={size}
        bg={bg}
        borderColor={borderColor}
        rows={rows}
        resize={isResizable ? 'vertical' : 'none'}
        placeholder={placeholder}
        _hover={{
          borderColor: useColorModeValue('gray.300', 'gray.500'),
        }}
        _focus={{
          borderColor: 'blue.500',
          boxShadow: 'outline',
        }}
        {...rest}
      />
      {error ? (
        <FormErrorMessage>{error}</FormErrorMessage>
      ) : helperText ? (
        <FormHelperText>{helperText}</FormHelperText>
      ) : null}
    </FormControl>
  );
};

export default TextArea;
