import 'package:flutter/foundation.dart';
import '../network/api_client.dart';

/// ==================== 通知枚举类型 ====================

/// 通知类型（与后端 NotificationType 枚举对应）
enum NotificationType {
  system,
  activity,
  reward,
  upgrade,
  announcement,
}

/// 通知优先级（与后端 NotificationPriority 枚举对应）
enum NotificationPriority {
  low,
  normal,
  high,
  urgent,
}

/// ==================== 通知数据模型 ====================

/// 单条通知项
///
/// 对应后端 MobileNotificationController GET /mobile/notifications 返回的列表项。
/// [requiresForceRead] 标记的通知在 APP 启动/恢复前台时强制弹窗展示。
class NotificationItem {
  final String id;
  final String title;
  final String content;
  final NotificationType type;
  final NotificationPriority priority;
  final String? imageUrl;
  final String? linkUrl;
  final DateTime? publishedAt;
  final bool isRead;
  final DateTime? readAt;

  /// 是否需要强制弹窗阅读（由管理员创建通知时配置）
  final bool requiresForceRead;

  NotificationItem({
    required this.id,
    required this.title,
    required this.content,
    required this.type,
    required this.priority,
    this.imageUrl,
    this.linkUrl,
    this.publishedAt,
    required this.isRead,
    this.readAt,
    this.requiresForceRead = false,
  });

  factory NotificationItem.fromJson(Map<String, dynamic> json) {
    return NotificationItem(
      id: json['id'] ?? '',
      title: json['title'] ?? '',
      content: json['content'] ?? '',
      type: _parseNotificationType(json['type']),
      priority: _parseNotificationPriority(json['priority']),
      imageUrl: json['imageUrl'],
      linkUrl: json['linkUrl'],
      publishedAt: json['publishedAt'] != null
          ? DateTime.tryParse(json['publishedAt'])
          : null,
      isRead: json['isRead'] ?? false,
      readAt: json['readAt'] != null ? DateTime.tryParse(json['readAt']) : null,
      requiresForceRead: json['requiresForceRead'] ?? false,
    );
  }

  static NotificationType _parseNotificationType(String? type) {
    switch (type) {
      case 'SYSTEM':
        return NotificationType.system;
      case 'ACTIVITY':
        return NotificationType.activity;
      case 'REWARD':
        return NotificationType.reward;
      case 'UPGRADE':
        return NotificationType.upgrade;
      case 'ANNOUNCEMENT':
        return NotificationType.announcement;
      default:
        return NotificationType.system;
    }
  }

  static NotificationPriority _parseNotificationPriority(String? priority) {
    switch (priority) {
      case 'LOW':
        return NotificationPriority.low;
      case 'NORMAL':
        return NotificationPriority.normal;
      case 'HIGH':
        return NotificationPriority.high;
      case 'URGENT':
        return NotificationPriority.urgent;
      default:
        return NotificationPriority.normal;
    }
  }

  /// 获取通知类型的中文名称
  String get typeName {
    switch (type) {
      case NotificationType.system:
        return '系统通知';
      case NotificationType.activity:
        return '活动通知';
      case NotificationType.reward:
        return '收益通知';
      case NotificationType.upgrade:
        return '升级通知';
      case NotificationType.announcement:
        return '公告';
    }
  }

  /// 获取通知类型的图标 emoji
  String get typeIcon {
    switch (type) {
      case NotificationType.system:
        return '🔔';
      case NotificationType.activity:
        return '🎉';
      case NotificationType.reward:
        return '💰';
      case NotificationType.upgrade:
        return '⬆️';
      case NotificationType.announcement:
        return '📢';
    }
  }
}

/// 通知列表 API 响应
class NotificationListResponse {
  final List<NotificationItem> notifications;
  final int total;
  final int unreadCount;

  NotificationListResponse({
    required this.notifications,
    required this.total,
    required this.unreadCount,
  });

  factory NotificationListResponse.fromJson(Map<String, dynamic> json) {
    final list = (json['notifications'] as List?)
            ?.map((e) => NotificationItem.fromJson(e as Map<String, dynamic>))
            .toList() ??
        [];
    return NotificationListResponse(
      notifications: list,
      total: json['total'] ?? list.length,
      unreadCount: json['unreadCount'] ?? 0,
    );
  }
}

/// ==================== 通知服务 ====================

/// 通知 API 服务
///
/// 通过 Kong 网关访问 mining-admin-service 的移动端通知接口：
/// - GET  /api/v2/mining-admin/mobile/notifications         获取通知列表
/// - GET  /api/v2/mining-admin/mobile/notifications/unread-count  获取未读数量
/// - POST /api/v2/mining-admin/mobile/notifications/mark-read    标记已读
class NotificationService {
  final ApiClient _apiClient;

  /// API 路径前缀（经 Kong 网关路由到 mining-admin-service）
  static const String _basePath = '/api/v2/mining-admin/mobile/notifications';

  NotificationService({required ApiClient apiClient}) : _apiClient = apiClient;

  /// 获取用户的通知列表
  ///
  /// [userSerialNum] 用户账号序列号（accountSequence）
  /// [type] 可选，按通知类型筛选
  /// [limit] 每页数量，默认 50
  /// [offset] 偏移量，默认 0
  Future<NotificationListResponse> getNotifications({
    required String userSerialNum,
    NotificationType? type,
    int limit = 50,
    int offset = 0,
  }) async {
    try {
      final queryParams = {
        'userSerialNum': userSerialNum,
        'limit': limit.toString(),
        'offset': offset.toString(),
      };
      if (type != null) {
        queryParams['type'] = type.name.toUpperCase();
      }

      final response = await _apiClient.get(
        _basePath,
        queryParameters: queryParams,
      );

      // 后端通过 TransformInterceptor 包装：{ success, data: { notifications, total, unreadCount }, timestamp }
      final data = response.data is Map && response.data['data'] != null
          ? response.data['data']
          : response.data;
      return NotificationListResponse.fromJson(data);
    } catch (e) {
      debugPrint('[NotificationService] 获取通知列表失败: $e');
      rethrow;
    }
  }

  /// 获取未读通知数量
  Future<int> getUnreadCount({required String userSerialNum}) async {
    try {
      final response = await _apiClient.get(
        '$_basePath/unread-count',
        queryParameters: {'userSerialNum': userSerialNum},
      );

      final data = response.data is Map && response.data['data'] != null
          ? response.data['data']
          : response.data;
      return data['unreadCount'] ?? 0;
    } catch (e) {
      debugPrint('[NotificationService] 获取未读数量失败: $e');
      return 0;
    }
  }

  /// 标记通知为已读
  ///
  /// [notificationId] 不传则标记全部为已读
  Future<bool> markAsRead({
    required String userSerialNum,
    String? notificationId,
  }) async {
    try {
      final body = {
        'userSerialNum': userSerialNum,
        if (notificationId != null) 'notificationId': notificationId,
      };

      final response = await _apiClient.post(
        '$_basePath/mark-read',
        data: body,
      );

      final data = response.data is Map && response.data['data'] != null
          ? response.data['data']
          : response.data;
      return data['success'] ?? false;
    } catch (e) {
      debugPrint('[NotificationService] 标记已读失败: $e');
      return false;
    }
  }

  /// 标记所有通知为已读（快捷方法）
  Future<bool> markAllAsRead({required String userSerialNum}) async {
    return markAsRead(userSerialNum: userSerialNum);
  }
}
