import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-return */
import { InputAdornment, TextField as MuiTextField } from "@mui/material";
import { ThemeProvider, useTheme } from "@mui/material/styles";
import cx from "classnames";
import { useEffect, useState } from "react";
import { Controller, } from "react-hook-form";
import Icon from "../Icon";
import Tooltip from "../Tooltip";
import { textFieldTheme } from "./TextFieldTheme";
import { setCurrentInput } from "./inputRefManager";
import "./styles.scss";
export default function TextField({ className, attr, label, createdForm, disabled, title, placeholder, multiline, maxChars, required, startAdornment, endAdornment, defaultEndAdornments = ["close"], showEndAdornment = true, onChange, onFocus, onKeyDown, onRemove, onBlur, rows = 4, infoText, inputRef, width = "100%", height, mask, blurMask, }) {
    const fieldName = attr;
    const outerTheme = useTheme();
    const [showPassword, setShowPassword] = useState(false);
    const [active, setActive] = useState(false);
    const [focus, setFocus] = useState(false);
    const [mouseOver, setMouseOver] = useState(false);
    const hasError = () => !!createdForm.formState.errors[attr];
    const hasLabel = !!label;
    // Custom height if provided; otherwise labeled single-line stays 48px, unlabeled shrinks with content, multiline fills
    const effectiveHeight = height !== undefined
        ? height
        : multiline
            ? "100%"
            : hasLabel
                ? "48px"
                : undefined;
    const getClassNames = cx("ds-input-text", className, {
        disabled: disabled,
        "ds-input-textarea": multiline,
    });
    const applyMask = (value, isBlur) => {
        if (typeof value === "string" && mask) {
            return mask(value, isBlur);
        }
        return value;
    };
    useEffect(() => {
        const currentValue = createdForm.getValues(fieldName);
        if (mask && currentValue) {
            const masked = applyMask(currentValue);
            if (masked !== currentValue) {
                createdForm.setValue(fieldName, masked, {
                    shouldValidate: false,
                });
            }
        }
    }, [attr, mask, createdForm, fieldName]);
    const getEndAdornmentIcon = (value) => {
        const adornments = [];
        if (defaultEndAdornments.length > 0) {
            // Check for password adornment
            if (defaultEndAdornments.includes("password")) {
                adornments.push(_jsx(Icon, { name: showPassword ? "visibility_off" : "visibility", size: "small", onClick: () => setShowPassword(!showPassword), className: "pointer" }, "password"));
            }
            // Check for info adornment
            if (defaultEndAdornments.includes("info") && infoText) {
                const infoTextElement = (_jsx(Icon, { name: "info", size: "small", className: "icon-info pointer" }));
                adornments.push(_jsx(Tooltip, { title: infoText, mode: "simple", children: _jsx("span", { children: infoTextElement }) }, "info"));
            }
            // Check for close adornment - show when value is not undefined and value is not equal to defaultValue
            if (defaultEndAdornments.includes("close") &&
                value !== undefined &&
                onRemove) {
                adornments.push(_jsx(Icon, { name: "close", size: "small", className: `${disabled ? "d-none" : ""} pointer`, onClick: () => onRemove && onRemove() }, "close"));
            }
        }
        // Append custom endAdornments if provided
        if (endAdornment && endAdornment.length > 0) {
            adornments.push(...endAdornment);
        }
        if (adornments.length === 0) {
            return null;
        }
        if (adornments.length === 1) {
            return adornments[0];
        }
        // Return multiple adornments wrapped in a div with spacing
        return _jsx("div", { className: "ds-end-adornments", children: adornments });
    };
    useEffect(() => {
        if (focus || mouseOver) {
            setActive(true);
        }
        else {
            setActive(false);
        }
    }, [focus, mouseOver]);
    return (_jsx("div", { className: getClassNames, style: { width }, children: _jsx(Controller, { name: fieldName, control: createdForm.control, render: ({ field }) => (_jsxs(ThemeProvider, { theme: textFieldTheme(outerTheme, { hasLabel }), children: [_jsx(MuiTextField, { ...field, inputRef: inputRef, label: label, value: field.value || "", type: defaultEndAdornments.includes("password")
                            ? showPassword
                                ? "text"
                                : "password"
                            : "text", fullWidth: true, required: required, disabled: disabled, variant: "filled", placeholder: !focus ? placeholder : "", color: "error", multiline: multiline, minRows: rows, slotProps: {
                            ...(hasLabel && {
                                inputLabel: {
                                    shrink: true,
                                },
                            }),
                            input: {
                                endAdornment: showEndAdornment && (_jsx(InputAdornment, { position: "end", children: getEndAdornmentIcon(field.value) })),
                                startAdornment: startAdornment && (_jsx(InputAdornment, { position: "start", children: startAdornment })),
                            },
                        }, onFocus: (e) => {
                            setCurrentInput(e.target, (e) => {
                                const value = applyMask(e.target.value);
                                field.onChange(value);
                                onChange && onChange(attr, value);
                            });
                            setFocus(true);
                            onFocus && onFocus(e);
                        }, onBlur: (e) => {
                            setFocus(false);
                            // Apply mask with blur flag to ensure proper formatting (e.g., 2 decimal places for currency)
                            const value = blurMask
                                ? blurMask(e.target.value)
                                : e.target.value;
                            if (value !== e.target.value) {
                                field.onChange(value);
                                onChange && onChange(attr, value);
                            }
                            onBlur && onBlur(e);
                        }, onMouseOver: () => setMouseOver(true), onMouseOut: () => setMouseOver(false), onKeyDown: (event) => onKeyDown && onKeyDown(event), onChange: (event) => {
                            const value = applyMask(event.target.value);
                            field.onChange(value);
                            onChange && onChange(attr, value);
                        }, sx: {
                            borderColor: disabled
                                ? "#BEBFC1"
                                : hasError()
                                    ? "#C6080A"
                                    : active
                                        ? "#1C83F4"
                                        : "#BEBFC1",
                            ".MuiInputLabel-root": {
                                color: disabled
                                    ? "#BEBFC1"
                                    : hasError()
                                        ? "#C6080A"
                                        : active
                                            ? "#1C83F4"
                                            : "#000000",
                            },
                            "& .MuiInputBase-inputMultiline": {
                                paddingTop: hasLabel ? "24px" : "8px",
                                paddingBottom: "16px",
                            },
                            ...(hasLabel &&
                                !multiline && {
                                "& .MuiInputBase-input": {
                                    paddingTop: "16px",
                                },
                            }),
                            "& .MuiInputAdornment-positionEnd": {
                                paddingTop: multiline ? "12px" : "0px",
                            },
                            ...(effectiveHeight !== undefined && {
                                height: effectiveHeight,
                            }),
                            "& .MuiInputBase-root": {
                                paddingTop: multiline ? "12px" : hasLabel ? "4px" : "0px",
                                height: effectiveHeight !== undefined ? "100%" : "auto",
                                alignItems: multiline ? "flex-start" : "center",
                            },
                        } }), maxChars && (_jsxs("div", { className: "character-counter", children: [field.value?.length || 0, "/", maxChars] })), title && !hasError() && _jsx("div", { className: "helper", children: title }), hasError() && (_jsx("div", { className: "helper error", children: String(createdForm.formState.errors[attr]?.message) }))] })) }) }));
}
