import { CustomDialog } from "@/components";
import { NullOr } from "@shared/utilities";
import { PropsWithChildren, useCallback, useMemo, useState } from "react";
import { UnsavedChangesNotifierProps } from "./useUnsavedChangesNotifier";
import { UnsavedWarnContext } from "./WarnAboutChangeContext";

export const UnsavedWarnProvider = ({ children }: PropsWithChildren) => {
  const [confirm, setConfirm] = useState<NullOr<UnsavedChangesNotifierProps>>(null);

  const [open, toggle] = useState(false);

  const show = useCallback(
    (confirmOptions: NullOr<UnsavedChangesNotifierProps>) => {
      setConfirm(confirmOptions);
      toggle(true);
    },
    [toggle, setConfirm]
  );

  const onConfirm = () => {
    confirm?.onConfirm?.();
    toggle(false);
  };

  const onCancel = () => {
    confirm?.onCancel?.();
    toggle(false);
  };

  const value = useMemo(() => ({ show }), [show]);

  return (
    <UnsavedWarnContext.Provider value={value}>
      {children}
      <CustomDialog
        //type='warning'
        onCancel={() => {
          //console.log("onCancel");
          onCancel();
        }}
        onConfirm={() => onConfirm()}
        title={confirm?.title}
        description={confirm?.subtitle}
        confirmLabel={confirm?.confirmText}
        cancelLabel={confirm?.cancelText}
        isOpen={open}
      />
    </UnsavedWarnContext.Provider>
  );
};
