/* eslint-disable @typescript-eslint/no-explicit-any */
import { useState, useRef, useCallback, useEffect, useMemo } from "react";
import { InputWidgetProps } from "./interface";
import { getValidateMessageFunc } from "./utils";
import { debounce } from "lodash-es";
import { getStyleMap } from "@/utils/getStyleMap";
import React from "react";
import { View } from "react-native"
import { HelperText, Icon, TextInput } from "react-native-paper";
import { InvalidMessageNative } from "../PublicSector/InvalidMessageNative";
import { StyleSheet } from "react-native";

export const InputNativeWidget = (props: InputWidgetProps) => {
  const {
    displayName,
    label,
    placeholder,
    variant,
    disabled,
    triggerEventHandler,
    type,
    startAdornmentIconName,     
    endAdornmentIconName,       
    required = false,
    multiline = false,       
    helperText = "",          
    defaultValue,
    value,
    numberOfLines,  // only android
    customRule,
    // tooltipText,    
    minLength,
    maxLength,
    pattern,
    error,
    regex,
    errorMessage,
    validateMessage,
    updateComponentRuntimeProps,
    deleteComponentRuntimeProps,
    handleUpdateDsl,
    hideValidationMessage,
    handleUpdateMultiExecutionResult,
    trueClasses = [], 
    falseClasses= [], 
    isClassTrue = true, 
    context,
    // colorScheme
  } = props;
  const inputRef = useRef<any>(null);
  const [inputValue, setInputValue] = useState(defaultValue);
  const val = useRef(defaultValue);
  useEffect(() => {
    setInputValue(defaultValue);
    // handleUpdateMultiExecutionResult([
    //   {
    //     displayName,
    //     value: {
    //       value: defaultValue || "",
    //     },
    //   },
    // ]);
  }, [defaultValue, displayName, handleUpdateMultiExecutionResult]);
  const handleValidate = useCallback(
    (value?: string) => {
      const message = getValidateMessageFunc(value, {
        hideValidationMessage: false,
        pattern: pattern,
        regex: regex,
        minLength: minLength,
        maxLength: maxLength,
        required: required,
      }, displayName);

      val.current = value;
      handleUpdateDsl({
        validateMessage: message,
        defaultValue: value,
      });
      return message;
    },
    [displayName, handleUpdateDsl, maxLength, minLength, pattern, regex, required]
  );
  const debounceOnChange = useRef(
    debounce(
      (
        value: string,
        triggerEventHandler: InputWidgetProps["triggerEventHandler"],
        options?: {
          hideValidationMessage?: InputWidgetProps["hideValidationMessage"];
          pattern?: InputWidgetProps["pattern"];
          regex?: InputWidgetProps["regex"];
          minLength?: InputWidgetProps["minLength"];
          maxLength?: InputWidgetProps["maxLength"];
          required?: InputWidgetProps["required"];
          customRule?: InputWidgetProps["customRule"];
        }
      ) => {
        new Promise((resolve) => {
          const message = getValidateMessageFunc(value, options, displayName);
          handleUpdateMultiExecutionResult([
            {
              displayName,
              value: {
                value: value || "",
                validateMessage: message,
              },
            },
          ]);
          resolve(true);
        }).then(() => {
          triggerEventHandler("change");
        });
      },
      180
    )
  );
  const handleOnChange = useCallback(
    (value: string) => {
      setInputValue(value);
      debounceOnChange.current(value, triggerEventHandler, {
        hideValidationMessage: hideValidationMessage,
        pattern: pattern,
        regex: regex,
        minLength: minLength,
        maxLength: maxLength,
        required: required,
        customRule: customRule,
      });
    },
    [
      customRule,
      hideValidationMessage,
      maxLength,
      minLength,
      pattern,
      regex,
      required,
      triggerEventHandler,
    ]
  );
  const clearValue = useCallback(() => {
    handleOnChange("");
  }, [handleOnChange]);
  useEffect(() => {
    updateComponentRuntimeProps({
      focus: () => {
        inputRef.current?.focus();
      },
      setValue: (value: boolean | string | number | void) => {
        if (typeof value === "string") {
          handleOnChange(value);
        }
      },
      clearValue: () => {
        clearValue();
      },
      validate: () => {
        return handleValidate(value);
      },
      clearValidation: () => {
        handleUpdateDsl({
          validateMessage: "",
        });
      },
    });

    return () => {
      deleteComponentRuntimeProps();
    };
  }, [
    clearValue,
    deleteComponentRuntimeProps,
    handleOnChange,
    handleUpdateDsl,
    handleValidate,
    updateComponentRuntimeProps,
    value,
  ]);
  const styles = useMemo(() => {
    return getStyleMap(trueClasses, falseClasses, true, context);
  }, [trueClasses, falseClasses, isClassTrue, context]);

  const flattenedStyles = StyleSheet.flatten(styles) || {}
  return (
    <>
      {/* {(type === "text" || type === "number") && ( */}
        <>
          <TextInput
            style={{ ...flattenedStyles, backgroundColor: "#ffffff" }}
            ref={inputRef}
            label={label}
            value={inputValue}
            onChangeText={handleOnChange}
            placeholder={placeholder}
            mode={variant}
            disabled={disabled}
            error={error}
            multiline={multiline}
            numberOfLines={numberOfLines}
            // activeOutlineColor={colorScheme}
            left={startAdornmentIconName && (
              <TextInput.Icon
                icon={startAdornmentIconName}
              />
            )}
            right={endAdornmentIconName && (
              <TextInput.Icon
                icon={endAdornmentIconName}
              />
            )}
          />
          {helperText && (
            <HelperText type={error ? 'error' : 'info'} disabled={disabled} style={flattenedStyles}>
              {helperText}
            </HelperText>
          )}

          {!hideValidationMessage && (
            <View
              style={flattenedStyles}
            >
              <InvalidMessageNative validateMessage={validateMessage && (errorMessage || validateMessage)} />
            </View>
          )}

        </>
      {/* )} */}
    </>
  );
};

InputNativeWidget.displayName = "InputNativeWidget";
export default InputNativeWidget;
