import type { ReactNode } from "react";

interface FieldProps {
    error?: string;
    label: string;
    name?: string;
    onBlur?: () => void;
    onChange?: (value: string) => void;
    readOnly?: boolean;
    value?: string;
    placeholder?: string;
    type?: "email" | "text" | "url";
}

export const Field = ({
    error,
    label,
    name,
    onBlur,
    onChange,
    placeholder,
    readOnly = false,
    type = "text",
    value = "",
}: FieldProps) => {
    return (
        <label className="form-field d-block">
            <span>{label}</span>
            <input
                aria-invalid={error ? true : undefined}
                className={`form-control${error ? " is-invalid" : ""}`}
                name={name}
                onBlur={onBlur}
                onChange={(event) => onChange?.(event.target.value)}
                placeholder={placeholder}
                readOnly={readOnly}
                type={type}
                value={value}
            />
            {error ? (
                <small className="form-field__error" role="alert">
                    {error}
                </small>
            ) : null}
        </label>
    );
};

interface TextareaFieldProps {
    error?: string;
    isEditing?: boolean;
    label: string;
    maxLength?: number;
    onBlur?: () => void;
    onChange?: (value: string) => void;
    value: string;
}

export const TextareaField = ({
    error,
    isEditing = true,
    label,
    maxLength = 500,
    onBlur,
    onChange,
    value,
}: TextareaFieldProps) => {
    return (
        <label className="form-field form-field--textarea d-block flex-grow-1">
            <span>{label}</span>
            <textarea
                aria-invalid={error ? true : undefined}
                className={`form-control${error ? " is-invalid" : ""}`}
                maxLength={maxLength}
                onBlur={onBlur}
                onChange={(event) => onChange?.(event.target.value)}
                readOnly={!isEditing}
                value={value}
            />
            <small>
                {value.length} / {maxLength} characters
            </small>
            {error ? (
                <small className="form-field__error" role="alert">
                    {error}
                </small>
            ) : null}
        </label>
    );
};

interface FormSectionProps {
    children: ReactNode;
    className?: string;
    title: string;
}

export const FormSection = ({
    children,
    className = "",
    title,
}: FormSectionProps) => {
    return (
        <section className={`portal-form-section ${className}`.trim()}>
            <h2>{title}</h2>
            {children}
        </section>
    );
};
