import type { AlertButton, AlertOptions } from 'react-native';

export interface DialogPayload {
  title?: string;
  message?: string;
  actions: AlertButton[];
  options?: AlertOptions;
}

type DialogListener = (payload: DialogPayload) => void;

let dialogListener: DialogListener | null = null;

export const bindDialogListener = (listener: DialogListener) => {
  dialogListener = listener;
  return () => {
    if (dialogListener === listener) {
      dialogListener = null;
    }
  };
};

export const showDialog = (payload: DialogPayload) => {
  dialogListener?.(payload);
};

export interface ConfirmOptions {
  title: string;
  message?: string;
  confirmText?: string;
  cancelText?: string;
  destructive?: boolean;
  onConfirm?: () => void;
  onCancel?: () => void;
}

export const showConfirm = (options: ConfirmOptions) => {
  showDialog({
    title: options.title,
    message: options.message,
    actions: [
      {
        text: options.cancelText ?? '取消',
        style: 'cancel',
        onPress: options.onCancel,
      },
      {
        text: options.confirmText ?? '确认',
        style: options.destructive ? 'destructive' : 'default',
        onPress: options.onConfirm,
      },
    ],
    options: { cancelable: true },
  });
};
