/* eslint-disable @typescript-eslint/no-explicit-any */
import { useEffect, useState } from "react";
import { BaseProps } from "../../Factory/BaseType";
import ConfirmationAlertView from "./ConfirmationAlertView";
import { useEffectiveStyle } from "../../utils/useEffectiveStyle";

export type ConfirmationAlertProps = BaseProps & {
  value: any;
  title: string;
  messageHeader?: string;
  messageBody?: string;
  iconUrl?: string;
  iconName?: string;
  confirmText?: string;
  cancelText?: string;
  onConfirm?: () => void;
  onCancel?: () => void;
  onModelUpdate?: (
    callBack: ((args: any) => void) | null,
    fieldName: string,
    value: any,
  ) => void;
  handleHeader?: (
    callback: (header: string) => void,
    header: string,
    viewModel?: Record<string, any>,
  ) => void;
  handleBody?: (
    callback: (body: string) => void,
    body: string,
    value?: any,
  ) => void;
};

const ConfirmationAlert = (props: ConfirmationAlertProps) => {
  useEffectiveStyle(props.widgetStyle);

  const [header, setHeader] = useState<string | undefined>(props.messageHeader);
  const [body, setBody] = useState<string | undefined>(props.messageBody);

  useEffect(() => {
    if (props.handleHeader) {
      props.handleHeader(setHeader, props.messageHeader ?? "", props.viewModel);
    } else {
      setHeader(props.messageHeader);
    }
  }, [props.messageHeader, props.viewModel, props.handleHeader]);

  useEffect(() => {
    if (props.handleBody) {
      props.handleBody(setBody, props.messageBody ?? "", props.value);
    } else {
      setBody(props.messageBody);
    }
  }, [props.messageBody, props.value, props.handleBody]);

  const handleCancel = () => {
    try {
      if (props.onCancel) {
        props.onCancel();
      } else if (props?.value?.onCancel) {
        props.value.onCancel();
      }
    } finally {
      props.onModelUpdate?.(null, props.screenDataField ?? "", null);
    }
  };

  const handleConfirm = async () => {
    try {
      if (props.onConfirm) {
        await props.onConfirm();
      } else if (props?.value?.onConfirm) {
        await props.value.onConfirm();
      }
    } finally {
      props.onModelUpdate?.(null, props.screenDataField ?? "", null);
    }
  };

  return (
    <ConfirmationAlertView
      {...props}
      messageHeader={header}
      messageBody={body}
      onConfirm={handleConfirm}
      onCancel={handleCancel}
    />
  );
};
export default ConfirmationAlert;
