import { HTMLAttributes, ReactNode } from 'react';
import { cn } from '../lib/cn';

export interface FormGroupProps extends Omit<HTMLAttributes<HTMLDivElement>, 'children'> {
  label?: ReactNode;
  helper?: ReactNode;
  error?: ReactNode;
  htmlFor?: string;
  required?: boolean;
  children?: ReactNode;
}

export function FormGroup({
  label,
  helper,
  error,
  htmlFor,
  required,
  className,
  children,
  ...rest
}: FormGroupProps) {
  const hasError = Boolean(error);
  return (
    <div className={cn('flex flex-col gap-1.5', className)} {...rest}>
      {label && (
        <label
          htmlFor={htmlFor}
          className="text-xs font-medium text-text"
        >
          {label}
          {required && <span className="ml-1 text-danger">*</span>}
        </label>
      )}
      {children}
      {hasError ? (
        <div className="flex items-center gap-1.5 text-xs text-danger">
          <svg
            width="12"
            height="12"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2.5"
            aria-hidden="true"
          >
            <circle cx="12" cy="12" r="10" />
            <line x1="12" y1="8" x2="12" y2="12" />
            <line x1="12" y1="16" x2="12.01" y2="16" />
          </svg>
          <span>{error}</span>
        </div>
      ) : (
        helper && <div className="text-xs text-text-3">{helper}</div>
      )}
    </div>
  );
}
