"use client";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React from "react";
import { Input, Textarea, Text } from "../../../components/atoms";
import { validateField, } from "../../../utils/validation";
export const FormField = ({ label, name, type = "text", value, onChange, placeholder, required = false, error: externalError, validation, className = "", testId, }) => {
    const [internalError, setInternalError] = React.useState(null);
    const [touched, setTouched] = React.useState(false);
    const handleChange = (e) => {
        onChange(e);
        setTouched(true);
        // Clear error when user starts typing
        if (internalError) {
            setInternalError(null);
        }
        // Run validation if provided
        if (validation && touched) {
            const validationError = validateField(e.target.value, validation, label);
            setInternalError(validationError);
        }
    };
    const handleBlur = () => {
        setTouched(true);
        if (validation) {
            const validationError = validateField(value, validation, label);
            setInternalError(validationError);
        }
    };
    const error = externalError || internalError;
    return (_jsxs("div", { className: `mb-4 ${className}`, "data-testid": testId, children: [_jsx("label", { htmlFor: name, className: "block mb-2", "data-testid": testId ? `${testId}.label` : undefined, children: _jsxs(Text, { variant: "body", className: "font-medium", children: [label, required && (_jsx("span", { className: "text-error-500 ml-1", "aria-label": "required", children: "*" }))] }) }), type === "textarea" ? (_jsx(Textarea, { id: name, name: name, value: value, onChange: handleChange, onBlur: handleBlur, placeholder: placeholder, required: required, error: error || undefined, testId: testId ? `${testId}.input` : undefined })) : (_jsx(Input, { id: name, name: name, type: type, value: value, onChange: handleChange, onBlur: handleBlur, placeholder: placeholder, required: required, error: error || undefined, testId: testId ? `${testId}.input` : undefined })), error && touched && (_jsx("span", { role: "alert", className: "text-error-500 mt-1 text-sm", "data-testid": testId ? `${testId}.error` : undefined, children: error }))] }));
};
export default FormField;
