import { NativeModules, Platform } from 'react-native';
import * as SecureStore from 'expo-secure-store';

export type CallDetectSettings = {
  /** Master switch — when false, no CRM peek / journal from call events. */
  enabled: boolean;
  /** Cellular / SIM dialer calls. */
  phone: boolean;
  /** WhatsApp voice/video calls (ConnectionService). */
  whatsapp: boolean;
};

const STORE_KEY = 'immotech_call_detect_v1';

const DEFAULTS: CallDetectSettings = {
  enabled: true,
  phone: true,
  whatsapp: false,
};

type NativeDetect = {
  getCallDetectSettings?: () => Promise<CallDetectSettings>;
  setCallDetectSettings?: (
    enabled: boolean,
    phone: boolean,
    whatsapp: boolean,
  ) => Promise<boolean>;
};

function native(): NativeDetect | null {
  return (NativeModules as { ImmotechCallWatch?: NativeDetect }).ImmotechCallWatch ?? null;
}

function normalize(raw: Partial<CallDetectSettings> | null | undefined): CallDetectSettings {
  return {
    enabled: raw?.enabled !== false,
    phone: raw?.phone !== false,
    whatsapp: raw?.whatsapp === true,
  };
}

async function readFallback(): Promise<CallDetectSettings> {
  try {
    const raw = await SecureStore.getItemAsync(STORE_KEY);
    if (!raw) return { ...DEFAULTS };
    return normalize(JSON.parse(raw) as Partial<CallDetectSettings>);
  } catch {
    return { ...DEFAULTS };
  }
}

async function writeFallback(s: CallDetectSettings): Promise<void> {
  try {
    await SecureStore.setItemAsync(STORE_KEY, JSON.stringify(s));
  } catch {
    // ignore
  }
}

/** Cached for callWatch (sync checks). */
let cache: CallDetectSettings = { ...DEFAULTS };
let cacheLoaded = false;

export function getCachedCallDetectSettings(): CallDetectSettings {
  return cache;
}

export async function loadCallDetectSettings(): Promise<CallDetectSettings> {
  if (Platform.OS === 'android') {
    const n = native();
    if (n?.getCallDetectSettings) {
      try {
        const s = normalize(await n.getCallDetectSettings());
        cache = s;
        cacheLoaded = true;
        await writeFallback(s);
        return s;
      } catch {
        // fall through
      }
    }
  }
  const s = await readFallback();
  cache = s;
  cacheLoaded = true;
  return s;
}

export async function saveCallDetectSettings(
  next: Partial<CallDetectSettings>,
): Promise<CallDetectSettings> {
  const base = cacheLoaded ? cache : await loadCallDetectSettings();
  const s = normalize({ ...base, ...next });
  // If master off, keep sub-flags for when user re-enables.
  cache = s;
  cacheLoaded = true;

  if (Platform.OS === 'android') {
    const n = native();
    if (n?.setCallDetectSettings) {
      try {
        await n.setCallDetectSettings(s.enabled, s.phone, s.whatsapp);
      } catch {
        // still persist JS fallback
      }
    }
  }
  await writeFallback(s);
  return s;
}

/** Whether callWatch / deep links may open CRM call UI. */
export function isCallDetectActive(settings: CallDetectSettings = cache): boolean {
  return settings.enabled && (settings.phone || settings.whatsapp);
}
