import 'package:get/get.dart';
import '../models/notification.dart';
import 'api_service.dart';

class NotificationService extends GetxController {
  static NotificationService get to => Get.find();

  final _apiService = ApiService();
  
  final notifications = <NotificationModel>[].obs;
  final unreadCount = 0.obs;
  final isLoading = false.obs;
  final hasMore = true.obs;

  int _currentPage = 1;
  final int _pageSize = 20;

  @override
  void onInit() {
    super.onInit();
    loadNotifications();
    loadUnreadCount();
  }

  /// Load notifications from API
  Future<void> loadNotifications({bool refresh = false}) async {
    if (refresh) {
      _currentPage = 1;
      notifications.clear();
      hasMore.value = true;
    }

    if (isLoading.value || !hasMore.value) return;

    try {
      isLoading.value = true;

      final response = await _apiService.get(
        '/notifications?page=$_currentPage&limit=$_pageSize',
      );

      if (response['success'] == true) {
        final List<dynamic> items = response['data']['notifications'] ?? [];
        final List<NotificationModel> newNotifications =
            items.map((json) => NotificationModel.fromJson(json)).toList();

        if (refresh) {
          notifications.value = newNotifications;
        } else {
          notifications.addAll(newNotifications);
        }

        // Check if there are more pages
        final pagination = response['data']['pagination'];
        if (pagination != null) {
          final currentPage = pagination['currentPage'];
          final totalPages = pagination['totalPages'];
          hasMore.value = currentPage < totalPages;
          if (hasMore.value) {
            _currentPage++;
          }
        }
      }
    } catch (e) {
      print('Error loading notifications: $e');
    } finally {
      isLoading.value = false;
    }
  }

  /// Load unread notification count
  Future<void> loadUnreadCount() async {
    try {
      final response = await _apiService.get('/notifications/unread-count');

      if (response['success'] == true) {
        unreadCount.value = response['data']['unread_count'] ?? 0;
      }
    } catch (e) {
      print('Error loading unread count: $e');
    }
  }

  /// Mark notification as read
  Future<bool> markAsRead(String notificationId) async {
    try {
      final response = await _apiService.put(
        '/notifications/$notificationId/read',
        {},
      );

      if (response['success'] == true) {
        // Update local notification
        final index = notifications.indexWhere((n) => n.id == notificationId);
        if (index != -1) {
          notifications[index] = notifications[index].copyWith(
            readAt: DateTime.now(),
            status: 'read',
          );
        }

        // Update unread count
        if (unreadCount.value > 0) {
          unreadCount.value--;
        }

        return true;
      }
      return false;
    } catch (e) {
      print('Error marking notification as read: $e');
      return false;
    }
  }

  /// Mark all notifications as read
  Future<bool> markAllAsRead() async {
    try {
      final response = await _apiService.put('/notifications/read-all', {});

      if (response['success'] == true) {
        // Update all local notifications
        notifications.value = notifications.map((n) {
          return n.copyWith(
            readAt: DateTime.now(),
            status: 'read',
          );
        }).toList();

        // Reset unread count
        unreadCount.value = 0;

        return true;
      }
      return false;
    } catch (e) {
      print('Error marking all as read: $e');
      return false;
    }
  }

  /// Delete notification
  Future<bool> deleteNotification(String notificationId) async {
    try {
      final response = await _apiService.delete('/notifications/$notificationId');

      if (response['success'] == true) {
        // Remove from local list
        notifications.removeWhere((n) => n.id == notificationId);

        // Update unread count if it was unread
        final notification = notifications.firstWhereOrNull((n) => n.id == notificationId);
        if (notification?.isUnread ?? false) {
          if (unreadCount.value > 0) {
            unreadCount.value--;
          }
        }

        return true;
      }
      return false;
    } catch (e) {
      print('Error deleting notification: $e');
      return false;
    }
  }

  /// Get notification statistics
  Future<Map<String, dynamic>?> getStats() async {
    try {
      final response = await _apiService.get('/notifications/stats');

      if (response['success'] == true) {
        return response['data'];
      }
      return null;
    } catch (e) {
      print('Error getting notification stats: $e');
      return null;
    }
  }

  /// Refresh notifications
  Future<void> refresh() async {
    await Future.wait([
      loadNotifications(refresh: true),
      loadUnreadCount(),
    ]);
  }

  /// Load more notifications (pagination)
  Future<void> loadMore() async {
    await loadNotifications(refresh: false);
  }

  /// Get unread notifications only
  List<NotificationModel> get unreadNotifications {
    return notifications.where((n) => n.isUnread).toList();
  }

  /// Get notifications by type
  List<NotificationModel> getByType(String type) {
    return notifications.where((n) => n.type == type).toList();
  }

  /// Get notifications by priority
  List<NotificationModel> getByPriority(String priority) {
    return notifications.where((n) => n.priority == priority).toList();
  }

  /// Get urgent notifications
  List<NotificationModel> get urgentNotifications {
    return notifications.where((n) => n.priority == 'urgent').toList();
  }
}

