/* eslint-disable @typescript-eslint/no-explicit-any */
import { useRef, useCallback, useEffect, useMemo } from "react";
import { OTPWidgetProps } from "./interface";
import { InvalidMessage } from "@/widgetLibrary/PublicSector/InvalidMessage";
import { AutoHeightContainer } from "@/widgetLibrary/PublicSector/AutoHeightContainer";
import { debounce } from "lodash-es";
import OTPInput from "./OTPInput";
import { getValidateMessageFunc } from "../InputWidget/utils";
import { getStyleMap } from "@/utils/getStyleMap";
// import { css } from "@emotion/react";

export const OTPWidget = (props: OTPWidgetProps) => {
  const {
    displayName,
    disabled,
    triggerEventHandler,
    type = "number", 
    context,
    required = false,
    separator="-",
    length=4,
    defaultValue,
    value,
    isClassTrue = true,
    trueClasses = [],
    falseClasses = [],
    tooltipText,
    boxWidth,
    boxHeight,
    validateMessage,
    updateComponentHeight,
    updateComponentRuntimeProps,
    deleteComponentRuntimeProps,
    handleUpdateDsl,
    hideValidationMessage,
    handleUpdateMultiExecutionResult,
  } = props;
  const inputRef = useRef<HTMLInputElement>(null);
  const val = useRef(defaultValue);
  useEffect(() => {
    handleUpdateMultiExecutionResult([
      {
        displayName,
        value: {
          value: defaultValue || "",
        },
      },
    ]);
  }, [defaultValue, displayName, handleUpdateMultiExecutionResult]);
  const handleValidate = useCallback(
    (value?: string) => {
      const message = getValidateMessageFunc(value, {
        hideValidationMessage: false,

        required: required,
      });

      val.current = value;
      handleUpdateDsl({
        validateMessage: message,
        defaultValue: value,
      });
      return message;
    },
    [handleUpdateDsl, required]
  );

  const debounceOnChange = useRef(
    debounce(
      (
        value: string,
        triggerEventHandler: OTPWidgetProps["triggerEventHandler"],
        options?: {
          hideValidationMessage?: OTPWidgetProps["hideValidationMessage"];
          required?: OTPWidgetProps["required"];
        }
      ) => {
        new Promise((resolve) => {
          const message = getValidateMessageFunc(value, options);
          handleUpdateMultiExecutionResult([
            {
              displayName,
              value: {
                value: value || "",
                validateMessage: message,
              },
            },
          ]);
          resolve(true);
        }).then(() => {
          triggerEventHandler("change");
        });
      },
      180
    )
  );
  const handleOnChange = useCallback(
    (value: string) => {
      debounceOnChange.current(value, triggerEventHandler, {
        hideValidationMessage: hideValidationMessage,

        required: required,
      });
    },
    [hideValidationMessage, 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 style = useMemo(() => {
      return getStyleMap(trueClasses, falseClasses, isClassTrue, context);
    }, [trueClasses, falseClasses, isClassTrue, context]);
  return (
    <>
  
        <OTPInput
          value={value}
          onChange={handleOnChange}
          required={required}
          disabled={disabled}
         style={style}
          title={tooltipText}
          type={type}
          separator={separator}
          length={length}
          boxWidth={boxWidth}
          boxHeight={boxHeight}
        />
     
      {!hideValidationMessage && (
        <div>
          <InvalidMessage validateMessage={validateMessage} />
        </div>
      )}
    </>
  );
};

OTPWidget.displayName = "InputWidget";
export default OTPWidget;
