import { classNames } from '@/lib/components/classNames';
import type { ReactNode } from 'react';
import styles from './FormField.module.css';

interface FormFieldProps {
  id: string;
  label: string;
  required?: boolean;
  optionalLabel?: string | undefined;
  supportingText?: string | undefined;
  error?: string | undefined;
  children: ReactNode;
  className?: string | undefined;
}

export function FormField({
  id,
  label,
  required = false,
  optionalLabel,
  supportingText,
  error,
  children,
  className,
}: FormFieldProps) {
  return (
    <div className={classNames(styles.field, error && styles.invalid, className)}>
      <label className={styles.label} htmlFor={id}>
        <span>{label}</span>
        {required ? (
          <span aria-hidden="true" className={styles.required}>
            *
          </span>
        ) : null}
        {!required && optionalLabel ? (
          <span className={styles.optional}>{optionalLabel}</span>
        ) : null}
      </label>
      {children}
      {supportingText ? (
        <p id={`${id}-help`} className={styles.help}>
          {supportingText}
        </p>
      ) : null}
      {error ? (
        <p id={`${id}-error`} className={styles.error}>
          <span aria-hidden="true">!</span> {error}
        </p>
      ) : null}
    </div>
  );
}

export function Fieldset({
  legend,
  children,
  className,
}: {
  legend: string;
  children: ReactNode;
  className?: string | undefined;
}) {
  return (
    <fieldset className={classNames(styles.fieldset, className)}>
      <legend className={styles.legend}>{legend}</legend>
      {children}
    </fieldset>
  );
}
