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

import { showDialog } from './dialogService';
import { showPrompt } from './promptService';

let installed = false;

const resolvePromptType = (title?: string) => {
  const source = title || '';
  if (source.includes('成功') || source.includes('完成') || source.includes('已')) return 'success' as const;
  if (source.includes('失败') || source.includes('错误') || source.includes('无法')) return 'error' as const;
  if (source.includes('请稍候') || source.includes('提示') || source.includes('权限')) return 'warning' as const;
  return 'info' as const;
};

export const installAlertOverride = () => {
  if (installed) return;
  installed = true;

  const nativeAlert = Alert.alert.bind(Alert);

  Alert.alert = (
    title?: string,
    message?: string,
    buttons?: AlertButton[],
    options?: AlertOptions
  ) => {
    const nextTitle = title || '提示';
    const nextMessage = message || '';
    const actionButtons = buttons ?? [];

    if (actionButtons.length === 0) {
      showPrompt({
        title: nextTitle,
        message: nextMessage || nextTitle,
        type: resolvePromptType(nextTitle),
      });
      return;
    }

    // 自定义对话框支持多按钮（含「主题模式」等 4 项）；Web 上原生 Alert 常不可用
    const MAX_CUSTOM_DIALOG_ACTIONS = 8;
    if (actionButtons.length <= MAX_CUSTOM_DIALOG_ACTIONS) {
      showDialog({
        title: nextTitle,
        message: nextMessage,
        actions: actionButtons,
        options,
      });
      return;
    }

    nativeAlert(nextTitle, nextMessage, buttons, options);
  };
};
