/* eslint-disable @typescript-eslint/no-explicit-any */
import { FC, useCallback, useEffect, useMemo } from "react";
import { AutoHeightContainer } from "@/widgetLibrary/PublicSector/AutoHeightContainer";
import { InvalidMessage } from "@/widgetLibrary/PublicSector/InvalidMessage/";
import { handleValidateCheck } from "@/widgetLibrary/PublicSector/InvalidMessage/utils";
import {
  // applyCenterLabelAndComponentWrapperStyle,
  applyValidateMessageWrapperStyle,
} from "@/page/App/components/scaleSquare/components/TransformWidgetWrapper/style";
import { formatSelectOptions } from "../SelectWidget/formSelectOptions";
import FormControl from "@mui/material/FormControl";
import {
  FormControlLabel,
  FormLabel,
  Radio,
  RadioGroup,
  useTheme,
} from "@mui/material";

export const WrappedRadioGroup: FC<any> = (props) => {
  const {
    value,
    disabled,
    options,
    direction,
    colorScheme,
    defaultValue,
    handleOnChange,
    getValidateMessage,
    handleUpdateDsl,
    required,
    label,
    name,
    styles,
    size,
    labelHidden,
  } = props;
  const theme = useTheme();
  const changeValue = (value?: unknown) => {
    new Promise((resolve) => {
      const message = getValidateMessage(value);
      handleUpdateDsl({
        validateMessage: message,
        value: value,
      });
      resolve(true);
    }).then(() => {
      handleOnChange?.();
    });
  };
  return (
    <FormControl
      sx={{
        justifyContent: "flex-start",
        display: "flex",
        width: "100%",
        flexDirection: "row",
      }}
    >
      <FormLabel
        required={required}
        sx={{
          ...styles,
          // width:"30%",
          paddingRight: "15px",
          display: "flex",
          alignItems: "center",
          color: colorScheme,
          textAlign: "left",
          "&.Mui-focused": {
            color: colorScheme,
          },
        }}
      >
        {!labelHidden ? label : null}
      </FormLabel>
      <RadioGroup
        name={name}
        sx={{ width: "70%", textAlign: "left" }}
        value={value}
        defaultValue={defaultValue}
        onChange={(e, val) => changeValue(val)}
        row={direction === "horizontal"}
      >
        {options?.map((option) => (
          <FormControlLabel
            key={option.key}
            value={option.value}
            control={
              <Radio
                disabled={disabled}
                style={{ color: colorScheme }}
                size={size}
              />
            }
            sx={{ color: theme.palette.text.primary }}
            label={option.label}
          />
        ))}
      </RadioGroup>
    </FormControl>
  );
};

WrappedRadioGroup.displayName = "WrappedRadioGroup";

export const RadioWidget: FC<any> = (props) => {
  const {
    value,
    optionConfigureMode,
    manualOptions,
    mappedOption,
    handleUpdateDsl,
    updateComponentRuntimeProps,
    deleteComponentRuntimeProps,
    labelPosition,
    label,
    labelWidth = 33,
    required,
    labelHidden,
    updateComponentHeight,
    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]);

  return (
    <>
      {/* <TooltipWrapper tooltipText={tooltipText} tooltipDisabled={!tooltipText}> */}
      <div style={{ paddingLeft: "5px" }}>
        <WrappedRadioGroup
          {...props}
          options={finalOptions}
          getValidateMessage={getValidateMessage}
          handleOnChange={handleOnChange}
        />
      </div>
      {!hideValidationMessage && (
        <div
          css={applyValidateMessageWrapperStyle(
            labelWidth,
            labelPosition,
            labelHidden || !label
          )}
        >
          <InvalidMessage validateMessage={validateMessage} />
        </div>
      )}
    </>
  );
};
RadioWidget.displayName = "RadioWidget";
export default RadioWidget;
