import { useCallback } from 'react';
import { Linking, Platform } from 'react-native';
import dialogService from '@/utils/ui/dialogService';
import LocationService from '@/services/location';
import * as Location from 'expo-location';
import { LOCATION_CONFIG } from '@/constants/location';

/**
 * useLocationSetupPrompt
 * - 统一的定位权限/服务提示工具
 * - 提供 showByError(err)、ensureReady()、dismissLocationPrompt() 能力
 */
export default function useLocationSetupPrompt() {
  // 统一作用域key，便于统一关闭
  const SCOPE_KEY = 'dialog.scope.location_setup';

  const openAndroidSettingsHome = useCallback(async () => {
    if (Platform.OS !== 'android') return Linking.openSettings().catch(() => {});
    try {
      // 优先使用 Android 原生 Action 跳转到设置首页
      if (typeof Linking.sendIntent === 'function') {
        await Linking.sendIntent('android.settings.SETTINGS');
        return;
      }
    } catch (_) {}
    try {
      // 备用：通过 intent URI 方式
      await Linking.openURL('intent:#Intent;action=android.settings.SETTINGS;end');
      return;
    } catch (_) {}
    try {
      // 兜底：回退到应用详情设置
      await Linking.openSettings();
    } catch (_) {}
  }, []);

  const showByError = useCallback((err) => {
    const msg = err?.message || '';
    const code = err?.code || '';
    let content = '无法获取位置信息，请检查定位相关设置后重试。';

    let isPermissionIssue = false;
    let isServiceIssue = false;

    if (code === 'PERMISSION_DENIED' || msg.includes('权限') || msg.toLowerCase().includes('permission')) {
      isPermissionIssue = true;
      content = '未授予定位权限，请前往系统设置在“位置信息/定位”中允许本应用使用位置权限。';
    } else if (
      code === 'UNAVAILABLE' ||
      msg.includes('位置服务') ||
      msg.toUpperCase().includes('GPS') ||
      msg.includes('定位服务') ||
      msg.includes('未开启')
    ) {
      isServiceIssue = true;
      content = '设备定位服务未开启或不可用，请在系统设置中开启GPS/定位服务后再试。';
    }

    dialogService.confirm({
      scopeKey: SCOPE_KEY,
      content,
      confirmText: '去设置',
      cancelText: '取消',
      onConfirm: () => {
        if (Platform.OS === 'android') {
          if (isServiceIssue) {
            // 设备定位服务未开启：跳转设置首页，兼容性更好
            openAndroidSettingsHome();
          } else {
            // 权限问题：保持跳转应用详情设置
            Linking.openSettings().catch(() => {});
          }
        } else {
          // iOS 统一到系统设置（会定位到应用设置）
          Linking.openSettings().catch(() => {});
        }
      },
    });
  }, [openAndroidSettingsHome]);

  // 统一文案：未开启精准定位权限（iOS/Android 共用）
  const showPreciseLocationNotEnabledPrompt = useCallback(() => {
    dialogService.confirm({
      scopeKey: SCOPE_KEY,
      content: '未开启精准定位权限,无法获取考勤打卡所需要的有效定位,请前往设置开启',
      confirmText: '去设置',
      cancelText: '继续',
      onConfirm: () => {
        // 精确位置开关位于应用的权限设置页
        Linking.openSettings().catch(() => {});
      },
    });
  }, []);

  // iOS 精准定位是否关闭：仅通过授权API判断，避免阻塞式高精度采样
  const isIOSPreciseLocationDisabled = useCallback(async () => {
    try {
      const hasAuthApi = typeof Location.getAccuracyAuthorizationAsync === 'function';
      if (hasAuthApi) {
        const auth = await Location.getAccuracyAuthorizationAsync();
        if (typeof auth === 'string') {
          return auth.toLowerCase().includes('reduced');
        }
        const AA = Location?.AccuracyAuthorization;
        if (typeof auth === 'number' && AA && typeof AA.Reduced === 'number') {
          return auth === AA.Reduced;
        }
      }
    } catch (_) {}
    // 无可用授权API或判断失败时，不阻塞流程，默认不视为关闭
    return false;
  }, []);

  // 统一关闭：仅关闭本作用域的弹窗
  const dismissLocationPrompt = useCallback(() => {
    dialogService.hideByScope(SCOPE_KEY);
  }, []);

  const ensureReady = useCallback(async () => {
    console.log('[ensureReady] 检查定位服务状态');
    try {
      const enabled = await LocationService.isLocationEnabled();
      if (!enabled) {
        showByError({ code: 'UNAVAILABLE', message: Platform.OS === 'android' ? '设备位置服务未开启，请在设置中开启GPS或位置服务' : '请在设备设置中开启定位服务' });
        return false;
      }

      // 先检查当前权限状态，已授权则不再触发权限请求，避免引发AppState抖动
      try {
        const hasPerm = await LocationService.hasLocationPermission();
        if (hasPerm) {
          // Android：已授权但仅为近似位置(coarse)时提示开启精准定位
          if (Platform.OS === 'android') {
            try {
              const detail = await Location.getForegroundPermissionsAsync();
              // 日志：Android 精度授权（coarse=未开启精准定位；fine=已开启精准定位）
              console.log('[LocationSetup] Android accuracy:', detail?.android?.accuracy || 'unknown');
              if (detail?.android?.accuracy === 'coarse') {
                showPreciseLocationNotEnabledPrompt();
              } else {
                dismissLocationPrompt();
              }
            } catch (_) {
              dismissLocationPrompt();
            }
          } else {
            // iOS：精准定位判断（iOS14+ 支持精确/模糊开关），并加入样本精度兜底（超时不阻塞）
            try {
              const disabled = await isIOSPreciseLocationDisabled();
              // 日志：iOS 精度授权（reduced=未开启精准定位；full=已开启精准定位）
              console.log('[LocationSetup] iOS accuracy authorization:', disabled ? 'reduced' : 'full');
              if (disabled) {
                showPreciseLocationNotEnabledPrompt();
              } else {
                // 精度样本兜底：若授权为 full，但样本精度持续大于阈值，则提示未开启精准定位
                const threshold = LOCATION_CONFIG?.ATTENDANCE?.accuracyThreshold ?? 100;
                let sample = null;
                try {
                  sample = await Promise.race([
                    LocationService.getCurrentPosition({ accuracy: Location.Accuracy.High, maximumAge: 3000, timeout: 1500 }),
                    new Promise((resolve) => setTimeout(() => resolve(null), 400)),
                  ]);
                } catch (_) {}
                const acc = sample?.coords?.accuracy;
                console.log('[LocationSetup] iOS fallback sample accuracy:', typeof acc === 'number' ? acc : 'unavailable');
                if (typeof acc === 'number' && acc > threshold) {
                  showPreciseLocationNotEnabledPrompt();
                } else {
                  dismissLocationPrompt();
                }
              }
            } catch (_) {
              // 检测异常不阻塞流程
              dismissLocationPrompt();
            }
          }
          return true;
        }
      } catch (_) {}

      // 未授权时再发起一次权限请求
      try {
        const ok = await LocationService.requestPermissions();
        if (ok) {
          // 授权成功后进行一次平台精度复核（不阻塞主流程）
          try {
            if (Platform.OS === 'android') {
              const detail = await Location.getForegroundPermissionsAsync();
              console.log('[LocationSetup] Android accuracy (post-ask):', detail?.android?.accuracy || 'unknown');
              if (detail?.android?.accuracy === 'coarse') {
                showPreciseLocationNotEnabledPrompt();
              } else {
                dismissLocationPrompt();
              }
            } else {
              const disabled = await isIOSPreciseLocationDisabled();
              console.log('[LocationSetup] iOS accuracy authorization (post-ask):', disabled ? 'reduced' : 'full');
              if (disabled) {
                showPreciseLocationNotEnabledPrompt();
              } else {
                const threshold = LOCATION_CONFIG?.ATTENDANCE?.accuracyThreshold ?? 100;
                let sample = null;
                try {
                  sample = await Promise.race([
                    LocationService.getCurrentPosition({ accuracy: Location.Accuracy.High, maximumAge: 3000, timeout: 1500 }),
                    new Promise((resolve) => setTimeout(() => resolve(null), 400)),
                  ]);
                } catch (_) {}
                const acc = sample?.coords?.accuracy;
                console.log('[LocationSetup] iOS fallback sample accuracy (post-ask):', typeof acc === 'number' ? acc : 'unavailable');
                if (typeof acc === 'number' && acc > threshold) {
                  showPreciseLocationNotEnabledPrompt();
                } else {
                  dismissLocationPrompt();
                }
              }
            }
          } catch (_) {
            dismissLocationPrompt();
          }
          return true;
        }
        // 正常情况下 granted 才会返回 true，这里兜底
        showByError({ code: 'PERMISSION_DENIED', message: '未授予定位权限' });
        return false;
      } catch (e) {
        // 请求失败或被拒绝时再提示
        showByError(e);
        return false;
      }
    } catch (e) {
      // 兜底：出现异常时也提示一次
      showByError(e);
      return false;
    }
  }, [showByError, dismissLocationPrompt]);

  return { showByError, ensureReady, dismissLocationPrompt };
}