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

/// 通知类型
enum NotificationType {
  system,
  activity,
  reward,
  upgrade,
  announcement,
}

/// 通知优先级
enum NotificationPriority {
  low,
  normal,
  high,
  urgent,
}

/// 通知项
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 '公告';
    }
  }

  /// 获取通知类型的图标
  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 '📢';
    }
  }
}

/// 通知列表响应
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,
    );
  }
}

/// 通知服务
class NotificationService {
  final ApiClient _apiClient;

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

  /// 获取用户的通知列表
  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(
        '/mobile/notifications',
        queryParameters: queryParams,
      );

      return NotificationListResponse.fromJson(response.data);
    } catch (e) {
      debugPrint('[NotificationService] 获取通知列表失败: $e');
      rethrow;
    }
  }

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

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

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

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

      return response.data['success'] ?? false;
    } catch (e) {
      debugPrint('[NotificationService] 标记已读失败: $e');
      return false;
    }
  }

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