import * as Haptics from 'expo-haptics';

interface VibrationConfig {
  enabled: boolean;
  onChatMessage: boolean;
  onGroupMessage: boolean;
  onNotification: boolean;
  style: Haptics.ImpactFeedbackStyle;
}

const defaultVibrationConfig: VibrationConfig = {
  enabled: true,
  onChatMessage: true,
  onGroupMessage: true,
  onNotification: true,
  style: Haptics.ImpactFeedbackStyle.Light,
};

let vibrationConfig: VibrationConfig = { ...defaultVibrationConfig };

export async function triggerVibration(
  type: 'light' | 'medium' | 'heavy' | 'success' | 'warning' | 'error' = 'light'
): Promise<void> {
  if (!vibrationConfig.enabled) {
    return;
  }

  try {
    switch (type) {
      case 'light':
        await Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
        break;
      case 'medium':
        await Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium);
        break;
      case 'heavy':
        await Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Heavy);
        break;
      case 'success':
        await Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success);
        break;
      case 'warning':
        await Haptics.notificationAsync(Haptics.NotificationFeedbackType.Warning);
        break;
      case 'error':
        await Haptics.notificationAsync(Haptics.NotificationFeedbackType.Error);
        break;
    }
  } catch (error) {
    console.error('[VibrationService] 震动反馈失败:', error);
  }
}

export async function vibrateOnMessage(messageType: 'chat' | 'group_message' | 'notification'): Promise<void> {
  if (!vibrationConfig.enabled) {
    return;
  }

  switch (messageType) {
    case 'chat':
      if (vibrationConfig.onChatMessage) {
        await triggerVibration('light');
      }
      break;
    case 'group_message':
      if (vibrationConfig.onGroupMessage) {
        await triggerVibration('light');
      }
      break;
    case 'notification':
      if (vibrationConfig.onNotification) {
        await triggerVibration('medium');
      }
      break;
  }
}

export function setVibrationConfig(config: Partial<VibrationConfig>): void {
  vibrationConfig = { ...vibrationConfig, ...config };
}

export function getVibrationConfig(): VibrationConfig {
  return { ...vibrationConfig };
}

export function setVibrationEnabled(enabled: boolean): void {
  vibrationConfig.enabled = enabled;
}
