
import { Description, Dialog as _Dialog, DialogPanel, DialogTitle, Transition } from '@headlessui/react';
import { useBlocker } from '@/shared/lib/hooks/use-blocker';
import { useBridge } from '@webview-bridge/react';
import { Fragment, ReactNode, useCallback } from 'react';
import { DialogButtons } from '@/shared/ui/dialogs/dialog-buttons';
import { bridge } from '@/bridge';

export interface DialogProps {
  open: boolean;
  onConfirmClick?: () => void | Promise<void>;
  onCancelClick?: () => void | Promise<void>;
  children?: ReactNode;
  title?: string | ReactNode;
  message?: string | ReactNode;
  shouldCloseOnBackdropClick?: boolean;
  buttonLabel?: string[];
  onClose: () => void;
  fullScreenMode?: boolean;
  afterLeave: () => void;
}

export const Dialog = ({
  open = false,
  onConfirmClick,
  onCancelClick,
  children,
  title,
  message,
  shouldCloseOnBackdropClick = false,
  buttonLabel = ['확인'],
  onClose,
  afterLeave,
  fullScreenMode = false,
}: DialogProps) => {
  const { nativeDialog, resetNativeDialog } = useBridge(bridge.store, (state) => state);

  const whenToBlock = useCallback(() => open, [open]);

  const blocker = useBlocker(whenToBlock);
  const nativeMessage = nativeDialog?.message;
  const displayMessage = nativeMessage || message;
  const handleClose = useCallback(() => {
    resetNativeDialog?.();
    onClose();
  }, []);
  const handleConfirm = useCallback(() => {
    blocker?.proceed?.();
    onConfirmClick?.();
    handleClose();
  }, []);
  const handleCancel = useCallback(() => {
    blocker?.reset?.();
    onCancelClick?.();
    handleClose();
  }, []);

  return (
    <Transition
      afterLeave={afterLeave}
      show={open}
      as={Fragment}
      enter="ease-out duration-300"
      enterFrom="opacity-0"
      enterTo="opacity-100"
      leave="ease-in duration-100"
      leaveFrom="opacity-100"
      leaveTo="opacity-0"
    >
      <_Dialog onClose={shouldCloseOnBackdropClick ? onClose : () => null} static={!shouldCloseOnBackdropClick}>
        <div
          id="cancelConfirmPopup"
          className="popup-overlay"
        >
          <div className="popup-bg-dim"></div>
          <DialogPanel
            as="div"
            className="popup-container"
          >
            {displayMessage && (
              <Description as="div" className={'popup-title'}>
                <p>{displayMessage}</p>
              </Description>
            )}
            {/* render buttonLabel */}
            {!fullScreenMode && (
              <DialogButtons buttonLabel={buttonLabel} onCancel={handleCancel} onConfirm={handleConfirm} />
            )}
          </DialogPanel>
        </div>
      </_Dialog>
    </Transition>
  );
};
