/* eslint-disable @typescript-eslint/no-explicit-any */
import { FC, useCallback, useEffect, useMemo } from "react";
import { InvalidMessage } from "@/widgetLibrary/PublicSector/InvalidMessage";
import {
  getValidateVFromString,
  handleValidateCheck,
} from "@/widgetLibrary/PublicSector/InvalidMessage/utils";
import { applyValidateMessageWrapperStyle } from "@/page/App/components/scaleSquare/components/TransformWidgetWrapper/style";
import { DatePicker } from "@mui/x-date-pickers/DatePicker";
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import dayjs from "dayjs";
import { AutoHeightContainer } from "../PublicSector/AutoHeightContainer";
import { FormControl } from "@mui/material";
import { getStyleMap } from "@/utils/getStyleMap";
 
export const WrappedDate: FC<any> = (props) => {
  const {
    value,
    label,
    required,
    format,
    validateMessage,
    // minDate,
    disabled,
    // maxDate,
    getValidateMessage,
    handleUpdateMultiExecutionResult,
    handleOnChange,
    displayName,
    readOnly,
    context,
    isClassTrue = true,
    trueClasses = [],
    falseClasses = [],
  } = props;
 
  const changeValue = (value?: unknown) => {
    new Promise((resolve) => {
      const message = getValidateMessage(value);
      handleUpdateMultiExecutionResult([
        {
          displayName,
          value: {
            value: value || "",
            validateMessage: message,
          },
        },
      ]);
      resolve(true);
    }).then(() => {
      handleOnChange?.();
    });
  };
  function isValidDate(dateString: any) {
    const date = new Date(dateString);
    return !isNaN(date?.getTime());
  }
  const style = useMemo(() => {
    return getStyleMap( trueClasses, falseClasses, isClassTrue,context);
  }, [ isClassTrue, trueClasses, falseClasses,context]);
  return (
    <div
      style={{
        paddingTop: "6px",
        width: "100%",
      }}
    >
      <FormControl
        fullWidth={true}
        variant="filled"
        size="small"
        sx={{ width: "100%" }}
      >
        <LocalizationProvider dateAdapter={AdapterDayjs}>
          <DatePicker
            label={label}
            sx={{ width: "100%", fontSize: "10px" }}
            css={style}
            format={format}
            onChange={(newValue) => {
              if (isValidDate(newValue)) {
                const formattedDate = dayjs(newValue).format(
                  `${format}THH:mm:ss.SSSZ`
                );
                changeValue(formattedDate);
              } else {
                changeValue(newValue);
              }
            }}
            // minDate={dayjs(minDate)}YYYY-MM-DD
            // maxDate={dayjs(maxDate)}
            disabled={disabled}
            readOnly={readOnly}
            value={isValidDate(value) ? dayjs(value, format) : null}
            slotProps={{
              textField: {
                size: "small",
                fullWidth: true,
                error: !!validateMessage,
                required: required,
                // helperText: validateMessage,
              },
            }}
          />
        </LocalizationProvider>
      </FormControl>
    </div>
  );
};
 
WrappedDate.displayName = "WrappedDate";
 
export const DateWidget: FC<any> = (props) => {
  const {
    value,
    handleUpdateDsl,
    updateComponentRuntimeProps,
    deleteComponentRuntimeProps,
    labelPosition,
    label,
    labelWidth = 33,
    required,
    labelHidden,
    pattern,
    regex,
    customRule,
    hideValidationMessage,
    updateComponentHeight,
    validateMessage,
    triggerEventHandler,
  } = props;
 
  const getValidateMessage = useCallback(
    (value?: unknown) => {
      if (!hideValidationMessage) {
        const message = handleValidateCheck({
          value: getValidateVFromString(value),
          required,
          customRule,
          pattern,
          regex,
        });
        const showMessage = message && message.length > 0;
        return showMessage ? message : "";
      }
      return "";
    },
    [customRule, hideValidationMessage, pattern, regex, required]
  );
 
  const handleValidate = useCallback(
    (value?: unknown) => {
      const message = getValidateMessage(value);
      handleUpdateDsl({
        validateMessage: message,
      });
      return message;
    },
    [getValidateMessage, handleUpdateDsl]
  );
 
  useEffect(() => {
    updateComponentRuntimeProps({
      setValue: (value: string) => {
        handleUpdateDsl({ value });
      },
      clearValue: () => {
        handleUpdateDsl({ value: "" });
      },
      validate: () => {
        return handleValidate(value);
      },
    });
    return () => {
      deleteComponentRuntimeProps();
    };
  }, [
    updateComponentRuntimeProps,
    handleUpdateDsl,
    deleteComponentRuntimeProps,
    handleValidate,
    value,
  ]);
 
  const handleOnChange = useCallback(() => {
    triggerEventHandler("change");
  }, [triggerEventHandler]);
  return (
    <>
      <WrappedDate
        {...props}
        getValidateMessage={getValidateMessage}
        handleOnChange={handleOnChange}
      />
      {!hideValidationMessage && (
        <div
          css={applyValidateMessageWrapperStyle(
            labelWidth,
            labelPosition,
            labelHidden || !label
          )}
        >
          <InvalidMessage validateMessage={validateMessage} />
        </div>
      )}
    </>
  );
};
DateWidget.displayName = "DateWidget";
 
export default DateWidget;
