/* eslint-disable @typescript-eslint/no-explicit-any */
import { FC, useCallback, useEffect, useMemo, useState } from "react";
// import { InvalidMessage } from "@/widgetLibrary/PublicSector/InvalidMessage/";
import { handleValidateCheck } from "@/widgetLibrary/PublicSector/InvalidMessage/utils";
import Autocomplete from "@mui/material/Autocomplete";
import { TextField } from "@mui/material";
import { formatSelectOptions } from "./formSelectOptions";
import { InvalidMessage } from "../PublicSector/InvalidMessage";

export const WrappedSelect: FC<any> = (props) => {
  const {
    validateMessage,
    value,
    options,
    placeholder,
    label,
    disabled,
    loading,
    readOnly,
    defaultValue,
    variant,
    required,
    handleUpdateMultiExecutionResult,
    handleOnChange,
    getValidateMessage,
    displayName,
    
  } = props;
  const [valueWithLabel, setValueWithLabel] = useState([]);
  const onChangeSelectValue = useCallback(
    (value: unknown) => {
      new Promise((resolve) => {
        const message = getValidateMessage(value);
        handleUpdateMultiExecutionResult([
          {
            displayName,
            value: {
              value: value || "",
              validateMessage: message,
            },
          },
        ]);
        resolve(true);
      }).then(() => {
        handleOnChange?.();
      });
    },
    [
      displayName,
      getValidateMessage,
      handleOnChange,
      handleUpdateMultiExecutionResult,
    ]
  );
  useEffect(() => {
    if (value || defaultValue) {
      const actualValues = options.find((e) => {
        return (
          value == e.value ||
          value == e.label ||
          defaultValue == e.value ||
          defaultValue == e.label
        );
      });
      setValueWithLabel(actualValues);
    }
  }, [value, options, defaultValue, options?.length]);

  return (
    <div
      style={{
        paddingTop: variant === "outlined" ? "6px" : "none",
        width: "100%",
      }}
    >
      <Autocomplete
        fullWidth
        options={options}
        value={valueWithLabel || ""}
        disabled={disabled}
        sx={{ fontSize: "6px" }}
        loading={loading}
        isOptionEqualToValue={()=>true}
        readOnly={readOnly}
        size="small"
        onChange={(_e, val) => {
          onChangeSelectValue(val?.value);
        }}
        renderInput={(params) => (
          <TextField
            {...params}
            size="small"
            placeholder={placeholder}
            label={label}
            error={!!validateMessage}
            variant={variant}
            
            required={required}
          />
        )}
      />
    </div>
  );
};

WrappedSelect.displayName = "WrappedSelect";

export const SelectWidget: FC<any> = (props) => {
  const {
    value,
    optionConfigureMode,
    mappedOption,
    manualOptions,
    handleUpdateDsl,
    updateComponentRuntimeProps,
    deleteComponentRuntimeProps,
    required,
    updateComponentHeight,
    // labelHidden,
    customRule,
    hideValidationMessage,
    validateMessage,
    triggerEventHandler,
  } = props;
  const finalOptions = useMemo(() => {
    return formatSelectOptions(
      optionConfigureMode,
      manualOptions,
      mappedOption
    );
  }, [optionConfigureMode, manualOptions, mappedOption]);
  const getValidateMessage = useCallback(
    (value: unknown) => {
      if (!hideValidationMessage) {
        const message = handleValidateCheck({
          value,
          required,
          customRule,
        });
        const showMessage = message && message.length > 0;
        return showMessage ? message : "";
      }
      return "";
    },
    [customRule, hideValidationMessage, required]
  );

  const handleValidate = useCallback(
    (value: unknown) => {
      const message = getValidateMessage(value);
      handleUpdateDsl({
        validateMessage: message,
      });
      return message;
    },
    [getValidateMessage, handleUpdateDsl]
  );

  useEffect(() => {
    updateComponentRuntimeProps({
      setValue: (value: any) => {
        handleUpdateDsl({ value });
      },
      clearValue: () => {
        handleUpdateDsl({ value: undefined });
      },
      validate: () => {
        return handleValidate(value);
      },
      clearValidation: () => {},
    });
    return () => {
      deleteComponentRuntimeProps();
    };
  }, [
    updateComponentRuntimeProps,
    handleUpdateDsl,
    deleteComponentRuntimeProps,
    handleValidate,
    value,
  ]);

  const handleOnChange = useCallback(() => {
    triggerEventHandler("change");
  }, [triggerEventHandler]);

  const handleOnFocus = useCallback(() => {
    triggerEventHandler("focus");
  }, [triggerEventHandler]);

  const handleOnBlur = useCallback(() => {
    triggerEventHandler("blur");
  }, [triggerEventHandler]);

  return (
    <>
      <WrappedSelect
        {...props}
        options={finalOptions}
        validateMessage={validateMessage}
        getValidateMessage={getValidateMessage}
        handleOnChange={handleOnChange}
        handleOnBlur={handleOnBlur}
        handleOnFocus={handleOnFocus}
      />
      {!hideValidationMessage && (
        <div style={{fontSize:"8px"}}>
          <InvalidMessage validateMessage={validateMessage} />
        </div>
      )}
    </>
  );
};
SelectWidget.displayName = "SelectWidget";
export default SelectWidget;
