import type { HealthKitPermissions } from 'react-native-health';
import AppleHealthKit from 'react-native-health';

const PERMISSIONS: HealthKitPermissions = {
  permissions: {
    read: [
      AppleHealthKit.Constants.Permissions.StepCount,
      AppleHealthKit.Constants.Permissions.ActiveEnergyBurned,
    ],
    write: [],
  },
};

export type TodayHealthData = {
  steps: number;
  activeEnergyBurned: number; // kilocalories
};

export async function ensureHealthPermissions(): Promise<boolean> {
  return new Promise((resolve) => {
    console.log('开始初始化HealthKit...');

    AppleHealthKit.initHealthKit(PERMISSIONS, (error) => {
      if (error) {
        console.error('HealthKit初始化失败:', error);
        // 常见错误处理
        if (typeof error === 'string') {
          if (error.includes('not available')) {
            console.warn('HealthKit不可用 - 可能在模拟器上运行或非iOS设备');
          }
        }
        resolve(false);
        return;
      }
      console.log('HealthKit初始化成功');
      resolve(true);
    });
  });
}

export async function fetchHealthDataForDate(date: Date): Promise<TodayHealthData> {
  console.log('开始获取指定日期健康数据...', date);

  const start = new Date(date);
  start.setHours(0, 0, 0, 0);
  const end = new Date(date);
  end.setHours(23, 59, 59, 999);

  const options = { startDate: start.toISOString(), endDate: end.toISOString() } as any;

  console.log('查询选项:', options);

  const steps = await new Promise<number>((resolve) => {
    AppleHealthKit.getStepCount(options, (err, res) => {
      if (err) {
        console.error('获取步数失败:', err);
        return resolve(0);
      }
      if (!res) {
        console.warn('步数数据为空');
        return resolve(0);
      }
      console.log('步数数据:', res);
      resolve(res.value || 0);
    });
  });

  const calories = await new Promise<number>((resolve) => {
    AppleHealthKit.getActiveEnergyBurned(options, (err, res) => {
      if (err) {
        console.error('获取消耗卡路里失败:', err);
        return resolve(0);
      }
      if (!res || !Array.isArray(res) || res.length === 0) {
        console.warn('卡路里数据为空或格式错误');
        return resolve(0);
      }
      console.log('卡路里数据:', res);
      // 求和该日内的所有记录（单位：千卡）
      const total = res.reduce((acc: number, item: any) => acc + (item?.value || 0), 0);
      resolve(total);
    });
  });

  console.log('指定日期健康数据获取完成:', { steps, calories });
  return { steps, activeEnergyBurned: calories };
}

export async function fetchTodayHealthData(): Promise<TodayHealthData> {
  return fetchHealthDataForDate(new Date());
}