import AsyncStorage from '@react-native-async-storage/async-storage';
import { Platform } from 'react-native';
import * as Notifications from 'expo-notifications';
import { setVibrationEnabled } from '../platform/messageVibrationService';

export const NOTIFICATION_PREF_KEYS = {
  vibration: 'vibration_enabled',
  push: 'notification_push_enabled',
  sound: 'notification_sound_enabled',
} as const;

export type NotificationPrefs = {
  pushEnabled: boolean;
  soundEnabled: boolean;
  vibrationEnabled: boolean;
};

const defaults: NotificationPrefs = {
  pushEnabled: true,
  soundEnabled: true,
  vibrationEnabled: true,
};

let cached: NotificationPrefs = { ...defaults };

export function getNotificationPreferencesSync(): NotificationPrefs {
  return { ...cached };
}

function parseBool(raw: string | null, fallback: boolean): boolean {
  if (raw === null) return fallback;
  try {
    return JSON.parse(raw) as boolean;
  } catch {
    return fallback;
  }
}

export async function loadNotificationPreferences(): Promise<NotificationPrefs> {
  try {
    const [vibrationRaw, pushRaw, soundRaw] = await Promise.all([
      AsyncStorage.getItem(NOTIFICATION_PREF_KEYS.vibration),
      AsyncStorage.getItem(NOTIFICATION_PREF_KEYS.push),
      AsyncStorage.getItem(NOTIFICATION_PREF_KEYS.sound),
    ]);
    cached = {
      vibrationEnabled: parseBool(vibrationRaw, defaults.vibrationEnabled),
      pushEnabled: parseBool(pushRaw, defaults.pushEnabled),
      soundEnabled: parseBool(soundRaw, defaults.soundEnabled),
    };
    setVibrationEnabled(cached.vibrationEnabled);
    return { ...cached };
  } catch {
    return { ...cached };
  }
}

export async function setVibrationPreference(enabled: boolean): Promise<void> {
  cached.vibrationEnabled = enabled;
  setVibrationEnabled(enabled);
  await AsyncStorage.setItem(NOTIFICATION_PREF_KEYS.vibration, JSON.stringify(enabled));
}

export async function setPushNotificationsPreference(enabled: boolean): Promise<void> {
  cached.pushEnabled = enabled;
  await AsyncStorage.setItem(NOTIFICATION_PREF_KEYS.push, JSON.stringify(enabled));
}

export async function setSoundPreference(enabled: boolean): Promise<void> {
  cached.soundEnabled = enabled;
  await AsyncStorage.setItem(NOTIFICATION_PREF_KEYS.sound, JSON.stringify(enabled));
}

export function registerNotificationPresentationHandler(): void {
  if (Platform.OS === 'web') return;

  Notifications.setNotificationHandler({
    handleNotification: async () => {
      const prefs = getNotificationPreferencesSync();
      return {
        shouldShowAlert: prefs.pushEnabled,
        shouldPlaySound: prefs.soundEnabled,
        shouldSetBadge: true,
        shouldShowBanner: prefs.pushEnabled,
        shouldShowList: prefs.pushEnabled,
      };
    },
  });
}
