import {
    forwardRef,
    useId,
    type InputHTMLAttributes,
    type TextareaHTMLAttributes,
    type ReactNode,
} from "react";
import s from "./Field.module.css";

interface BaseProps
{
    label?: ReactNode;
    hint?: ReactNode;
    error?: ReactNode;
    required?: boolean;
}

export interface TextFieldProps
    extends Omit<InputHTMLAttributes<HTMLInputElement>, "size">,
            BaseProps
{}

export interface TextAreaProps
    extends TextareaHTMLAttributes<HTMLTextAreaElement>,
            BaseProps
{}

function Wrap(props: {
    id: string;
    label?: ReactNode;
    hint?: ReactNode;
    error?: ReactNode;
    required?: boolean;
    children: ReactNode;
})
{
    const { id, label, hint, error, required, children } = props;
    return (
        <div className={s.field}>
            {label && (
                <label
                    htmlFor={id}
                    className={[ s.label, required ? s.required : "" ].filter(Boolean).join(" ")}
                >
                    {label}
                </label>
            )}
            {children}
            {error
                ? <div className={`${s.error} justify`} role="alert" data-jz-level="paragraph">{error}</div>
                : hint ? <div className={`${s.hint} justify`} data-jz-level="paragraph">{hint}</div> : null}
        </div>
    );
}

export const TextField = forwardRef<HTMLInputElement, TextFieldProps>((props, ref) =>
{
    const { id, label, hint, error, required, className, ...rest } = props;
    const auto = useId();
    const inputId = id ?? auto;

    const cls = [ s.input, error ? s.invalid : "", className ?? "" ]
        .filter(Boolean).join(" ");

    return (
        <Wrap id={inputId} label={label} hint={hint} error={error} required={required}>
            <input
                ref={ref}
                id={inputId}
                className={cls}
                aria-invalid={error ? true : undefined}
                {...rest}
            />
        </Wrap>
    );
});
TextField.displayName = "TextField";

export const TextArea = forwardRef<HTMLTextAreaElement, TextAreaProps>((props, ref) =>
{
    const { id, label, hint, error, required, className, ...rest } = props;
    const auto = useId();
    const inputId = id ?? auto;

    const cls = [ s.textarea, error ? s.invalid : "", className ?? "" ]
        .filter(Boolean).join(" ");

    return (
        <Wrap id={inputId} label={label} hint={hint} error={error} required={required}>
            <textarea
                ref={ref}
                id={inputId}
                className={cls}
                aria-invalid={error ? true : undefined}
                {...rest}
            />
        </Wrap>
    );
});
TextArea.displayName = "TextArea";
