/* eslint-disable @typescript-eslint/no-explicit-any */
import { useCallback, useEffect, useMemo } from "react";
import FormControl from "@mui/material/FormControl";
import Checkbox from "@mui/material/Checkbox";
import FormControlLabel from "@mui/material/FormControlLabel";
import { AutoHeightContainer } from "@/widgetLibrary/PublicSector/AutoHeightContainer";
import { getIcon } from "./icons";
import { applyValidateMessageWrapperStyle } from "@/page/App/components/scaleSquare/components/TransformWidgetWrapper/style";
import { InvalidMessage } from "../PublicSector/InvalidMessage";
import { handleValidateCheck } from "../PublicSector/InvalidMessage/utils";
import { getStyleMap } from "@/utils/getStyleMap";
import { useTheme } from "@mui/material";
import theme from "@/theme";

export const CheckboxContainer = ({
  disabled = false,
  error = false,
  labelPlacement = "start",
  isClassTrue = true,
  trueClasses = [],
  falseClasses = [],
  iconName,
  checkedIconName,
  value = false,
  handleUpdateDsl,
  updateComponentRuntimeProps,
  deleteComponentRuntimeProps,
  label = "Check",
  labelWidth = 33,
  context,
  required = false,
  labelHidden = false,
  tooltipText = "",
  customRule,
  triggerEventHandler,
  hideValidationMessage,
  validateMessage,
}: //
any) => {
  const theme = useTheme()
  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]
  );
  const changeValue = (value?: unknown) => {
    new Promise((resolve) => {
      const message = getValidateMessage(value);
      handleUpdateDsl({
        validateMessage: message,
        value: value,
      });
      resolve(true);
    }).then(() => {
      handleOnChange?.();
    });
  };
  const handleOnChange = useCallback(() => {
    triggerEventHandler("change");
  }, [triggerEventHandler]);
  useEffect(() => {
    updateComponentRuntimeProps({
      setValue: (value: any) => {
        handleUpdateDsl({ value });
      },
      clearValue: () => {
        handleUpdateDsl({ value: undefined });
      },
      validate: () => {
        return handleValidate(value);
      },
      clearValidation: () => {},
    });
    return () => {
      deleteComponentRuntimeProps();
    };
  }, [
    deleteComponentRuntimeProps,
    handleUpdateDsl,
    handleValidate,
    updateComponentRuntimeProps,
    value,
  ]);
  const style = useMemo(() => {
    return getStyleMap(trueClasses, falseClasses, isClassTrue, context);
  }, [trueClasses, falseClasses, isClassTrue, context]);
  return (
    <>
      <FormControl
        error={error}
        css={style}
        sx={{ display: "flex", justifyContent: "flex-start" }}
      >
        <FormControlLabel
          control={
            <Checkbox
              checked={value}
              disabled={disabled}
              onChange={(event) => {
                changeValue(event.target.checked);
              }}
              size="large"
              defaultValue={value}
              required={required}
              title={tooltipText}
            
              {...makeIconProps(iconName, checkedIconName)}
            />
          }
          label={label}
          labelPlacement={labelPlacement}
          sx={{ display: "flex", justifyContent: "flex-start",color:theme.palette.text.primary }}
        />
      </FormControl>
      {!hideValidationMessage && (
        <div
          css={applyValidateMessageWrapperStyle(
            labelWidth,
            labelHidden || !label
          )}
        >
          <InvalidMessage validateMessage={validateMessage} />
        </div>
      )}
      </>
  );
};

CheckboxContainer.displayName = "CheckboxContainer";
function makeIconProps(iconName, checkedIconName) {
  let obj = {};
  if (iconName) {
    obj = { icon: getIcon(iconName) };
  } else {
    obj = {};
  }
  if (checkedIconName) {
    obj = { ...obj, checkedIcon: getIcon(checkedIconName) };
  }
  return obj;
}
