import '../core/api_client.dart';

class InAppNotification {
  final String id;
  final String type;
  final String title;
  final String message;
  final String severity;
  final String? actionType;
  final String? actionTargetId;
  final bool isRead;
  final DateTime createdAt;

  const InAppNotification({
    required this.id,
    required this.type,
    required this.title,
    required this.message,
    required this.severity,
    this.actionType,
    this.actionTargetId,
    required this.isRead,
    required this.createdAt,
  });

  factory InAppNotification.fromJson(Map<String, dynamic> json) =>
      InAppNotification(
        id: json['id']?.toString() ?? '',
        type: json['type']?.toString() ?? '',
        title: json['title']?.toString() ?? '健康提醒',
        message: json['message']?.toString() ?? '',
        severity: json['severity']?.toString() ?? 'info',
        actionType: json['actionType']?.toString(),
        actionTargetId: json['actionTargetId']?.toString(),
        isRead: json['isRead'] == true,
        createdAt:
            DateTime.tryParse(json['createdAt']?.toString() ?? '') ??
            DateTime.now(),
      );

  InAppNotification copyWith({bool? isRead}) => InAppNotification(
    id: id,
    type: type,
    title: title,
    message: message,
    severity: severity,
    actionType: actionType,
    actionTargetId: actionTargetId,
    isRead: isRead ?? this.isRead,
    createdAt: createdAt,
  );
}

class InAppNotificationHistory {
  final int unreadCount;
  final List<InAppNotification> items;

  const InAppNotificationHistory({
    required this.unreadCount,
    required this.items,
  });
}

class InAppNotificationService {
  final ApiClient _api;

  const InAppNotificationService(this._api);

  Future<List<InAppNotification>> getPending() async {
    final response = await _api.get('/api/notifications/pending');
    final items = response.data['data'] as List? ?? const [];
    return items
        .whereType<Map>()
        .map(
          (item) => InAppNotification.fromJson(Map<String, dynamic>.from(item)),
        )
        .where((item) => item.id.isNotEmpty)
        .toList();
  }

  Future<void> acknowledge(String id) async {
    await _api.post('/api/notifications/$id/acknowledge');
  }

  Future<void> markAllRead() async {
    await _api.post('/api/notifications/read-all');
  }

  Future<InAppNotificationHistory> getHistory() async {
    final response = await _api.get('/api/notifications');
    final data = response.data['data'] as Map? ?? const {};
    final rawItems = data['items'] as List? ?? const [];
    return InAppNotificationHistory(
      unreadCount: data['unreadCount'] as int? ?? 0,
      items: rawItems
          .whereType<Map>()
          .map(
            (item) =>
                InAppNotification.fromJson(Map<String, dynamic>.from(item)),
          )
          .where((item) => item.id.isNotEmpty)
          .toList(),
    );
  }

  Future<void> delete(String id) async {
    await _api.delete('/api/notifications/$id');
  }
}
