import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'auth_provider.dart';
import '../services/health_service.dart';

final exerciseServiceProvider = Provider<ExerciseService>((ref) {
  return ExerciseService(ref.watch(apiClientProvider));
});

/// 健康数据服务
final healthServiceProvider = Provider<HealthService>((ref) {
  return HealthService(ref.watch(apiClientProvider));
});

final userServiceProvider = Provider<UserService>((ref) {
  return UserService(ref.watch(apiClientProvider));
});

final medicationServiceProvider = Provider<MedicationService>((ref) {
  return MedicationService(ref.watch(apiClientProvider));
});

final dietServiceProvider = Provider<DietService>((ref) {
  return DietService(ref.watch(apiClientProvider));
});

final consultationServiceProvider = Provider<ConsultationService>((ref) {
  return ConsultationService(ref.watch(apiClientProvider));
});

/// 最新健康数据 Provider
final latestHealthProvider = FutureProvider<Map<String, dynamic>>((ref) async {
  final service = ref.watch(healthServiceProvider);
  return service.getLatest();
});

/// AI 录入数据后调用，刷新侧边栏
void refreshHealthData(WidgetRef ref) {
  ref.invalidate(latestHealthProvider);
  ref.invalidate(medicationListProvider);
}

/// 用药列表 Provider
final medicationListProvider = FutureProvider<List<Map<String, dynamic>>>((ref) async {
  final service = ref.watch(medicationServiceProvider);
  return service.getList();
});

final medicationReminderProvider = FutureProvider<List<Map<String, dynamic>>>((ref) async {
  final service = ref.watch(medicationServiceProvider);
  return service.getReminders();
});

/// 医生列表 Provider
final doctorListProvider = FutureProvider<List<Map<String, dynamic>>>((ref) async {
  final service = ref.watch(consultationServiceProvider);
  try {
    return await service.getDoctors().timeout(const Duration(seconds: 8));
  } catch (_) {
    return _fallbackDoctors;
  }
});

const _fallbackDoctors = [
  {
    'id': 'doc_1',
    'name': '张医生',
    'title': '主任医师',
    'department': '心内科',
    'introduction': '擅长冠心病、高血压术后管理，20年临床经验',
  },
  {
    'id': 'doc_2',
    'name': '李医生',
    'title': '副主任医师',
    'department': '内分泌科',
    'introduction': '擅长糖尿病、甲状腺疾病管理，15年临床经验',
  },
  {
    'id': 'doc_3',
    'name': '王医生',
    'title': '主治医师',
    'department': '营养科',
    'introduction': '擅长术后营养指导、饮食方案制定，10年临床经验',
  },
];

/// 问诊配额 Provider
final consultationQuotaProvider = FutureProvider<Map<String, dynamic>>((ref) async {
  final service = ref.watch(consultationServiceProvider);
  return service.getQuota();
});

/// 当前运动计划 Provider
final currentExercisePlanProvider = FutureProvider<Map<String, dynamic>?>((ref) async {
  final service = ref.watch(exerciseServiceProvider);
  try {
    return await service.getCurrentPlan().timeout(const Duration(seconds: 8));
  } catch (_) {
    final today = DateTime.now();
    final monday = today.subtract(Duration(days: today.weekday - 1));
    return {
      'weekStartDate': '${monday.year}-${monday.month.toString().padLeft(2, '0')}-${monday.day.toString().padLeft(2, '0')}',
      'items': List.generate(7, (i) => {
        'id': 'local_$i',
        'dayOfWeek': i,
        'exerciseType': i == 2 || i == 5 ? '休息' : '散步',
        'durationMinutes': i == 2 || i == 5 ? 0 : 30,
        'isRestDay': i == 2 || i == 5,
        'isCompleted': false,
      }),
    };
  }
});

/// 拍照/相册直接触发（无需跳转页面）
final cameraActionProvider = NotifierProvider<CameraActionNotifier, String?>(CameraActionNotifier.new);

class CameraActionNotifier extends Notifier<String?> {
  @override String? build() => null;
  void trigger(String action) => state = action;
  void clear() => state = null;
}
