import { Children, isValidElement } from 'react';
import { Label } from '@/components/Label';

export type FormFieldProps = {
    children: React.ReactNode;
    label: React.ReactNode;
    labelFor?: string;
    isRequired?: boolean;
    error?: string;
};

export function FormField({
    children,
    label,
    labelFor,
    isRequired,
    error,
}: FormFieldProps) {
    const inputId = Children.map(children, child => {
        if (isValidElement(child)) {
            // @ts-expect-error expects that child has id prop
            return child.props?.id;
        }
    })
        ?.flat()
        .pop();

    return (
        <div className="flex flex-col gap-1">
            <Label htmlFor={labelFor || inputId}>
                <span>{label}</span>
                {isRequired ? <span>*</span> : null}
            </Label>
            {children}
            {error && <span className="text-12 text-red">{error}</span>}
        </div>
    );
}
