import React from 'react';
import type { ReactNode } from 'react';
import {
  FormControl,
  FormLabel,
  FormErrorMessage,
  FormHelperText,
} from '@chakra-ui/react';

export interface FormGroupProps {
  /**
   * Label for the form group
   */
  label?: string;

  /**
   * Whether the form group is required
   */
  isRequired?: boolean;

  /**
   * Whether the form group is invalid
   */
  isInvalid?: boolean;

  /**
   * Error message to display when the form group is invalid
   */
  errorMessage?: string;

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

  /**
   * Children to render inside the form group
   */
  children: ReactNode;

  /**
   * Additional props to pass to the form control
   */
  [key: string]: any;
}

/**
 * FormGroup component for grouping form elements with labels, error messages, and helper text
 */
export const FormGroup: React.FC<FormGroupProps> = ({
  label,
  isRequired = false,
  isInvalid = false,
  errorMessage,
  helperText,
  children,
  ...rest
}) => {
  return (
    <FormControl isRequired={isRequired} isInvalid={isInvalid} mb={4} {...rest}>
      {label && <FormLabel>{label}</FormLabel>}
      {children}
      {isInvalid && errorMessage && <FormErrorMessage>{errorMessage}</FormErrorMessage>}
      {helperText && !isInvalid && <FormHelperText>{helperText}</FormHelperText>}
    </FormControl>
  );
};

export default FormGroup;
