import 'dart:convert';
import '../../../core/services/api_service.dart';
import '../../../core/services/secure_storage_service.dart';
import 'models/chatbot_rule_model.dart';
import 'models/contact_model.dart';
import 'models/plan_model.dart';
import 'models/super_admin_stats_model.dart';
import 'models/whatsapp_status_model.dart';
import 'models/meta_session_model.dart';

class DashboardRepository {
  final ApiService _apiService = ApiService();
  final SecureStorageService _secureStorage = SecureStorageService();

  // English: Helper to retrieve token from secure storage. Throws exception if token is missing.
  // Arabic: دالة مساعدة لاسترداد الرمز من التخزين الآمن. تطلق استثناء إذا كان الرمز مفقودًا.
  Future<String> _getToken() async {
    final token = await _secureStorage.readToken();
    if (token == null || token.isEmpty) {
      throw Exception('أنت غير مصرح لك بالوصول، يرجى إعادة تسجيل الدخول');
    }
    return token;
  }

  // English: Load the active WhatsApp connection session status.
  // Arabic: تحميل حالة اتصال جلسة الواتساب النشطة.
  Future<WhatsAppStatusModel?> getWhatsAppStatus() async {
    final token = await _getToken();
    final response = await _apiService.getWhatsAppStatus(token);

    if (response.statusCode == 200) {
      final decoded = jsonDecode(response.body) as Map<String, dynamic>;
      final statusData = decoded['data'] as Map<String, dynamic>?;
      if (statusData == null) return null;
      return WhatsAppStatusModel.fromJson(statusData);
    } else {
      throw Exception('فشل في جلب حالة الواتساب');
    }
  }

  // English: Load available subscription plans.
  // Arabic: تحميل باقات الاشتراك المتاحة.
  Future<List<PlanModel>> getPlans() async {
    final token = await _getToken();
    final response = await _apiService.getPlans(token);

    if (response.statusCode == 200) {
      final decoded = jsonDecode(response.body) as Map<String, dynamic>;
      final list = decoded['data'] as List<dynamic>? ?? [];
      return list.map((item) => PlanModel.fromJson(item as Map<String, dynamic>)).toList();
    } else {
      throw Exception('فشل في جلب الباقات المتاحة');
    }
  }

  // English: Load CRM contacts directory.
  // Arabic: تحميل دليل جهات اتصال إدارة العملاء.
  Future<List<ContactModel>> getContacts() async {
    final token = await _getToken();
    final response = await _apiService.getContacts(token);

    if (response.statusCode == 200) {
      final decoded = jsonDecode(response.body) as Map<String, dynamic>;
      final list = decoded['data'] as List<dynamic>? ?? [];
      return list.map((item) => ContactModel.fromJson(item as Map<String, dynamic>)).toList();
    } else {
      throw Exception('فشل في جلب جهات الاتصال');
    }
  }

  // English: Create a new contact inside remote CRM directory.
  // Arabic: إنشاء جهة اتصال جديدة داخل دليل إدارة العملاء البعيد.
  Future<void> addContact(String name, String phone) async {
    final token = await _getToken();
    final response = await _apiService.addContact(token, name, phone);

    if (response.statusCode == 201 || response.statusCode == 200) {
      return;
    } else if (response.statusCode == 409) {
      throw Exception('رقم الهاتف هذا مسجل بالفعل في جهات الاتصال الخاصة بك');
    } else {
      final decoded = jsonDecode(response.body) as Map<String, dynamic>;
      final error = decoded['message'] as String? ?? 'فشل في إضافة جهة الاتصال';
      throw Exception(error);
    }
  }

  // English: Load chatbot auto-reply rules.
  // Arabic: تحميل قواعد الرد الآلي لروبوت الدردشة.
  Future<List<ChatbotRuleModel>> getChatbotRules() async {
    final token = await _getToken();
    final response = await _apiService.getChatbotRules(token);

    if (response.statusCode == 200) {
      final decoded = jsonDecode(response.body) as Map<String, dynamic>;
      final list = decoded['data'] as List<dynamic>? ?? [];
      return list.map((item) => ChatbotRuleModel.fromJson(item as Map<String, dynamic>)).toList();
    } else {
      throw Exception('فشل في جلب قواعد الرد الآلي');
    }
  }

  // English: Load platform statistics (Super Admin only).
  // Arabic: تحميل إحصائيات المنصة (للمشرف العام فقط).
  Future<SuperAdminStatsModel> getAdminStats() async {
    final token = await _getToken();
    final response = await _apiService.getAdminStats(token);

    if (response.statusCode == 200) {
      final decoded = jsonDecode(response.body) as Map<String, dynamic>;
      final statsData = decoded['data'] as Map<String, dynamic>?;
      if (statsData == null) {
        throw Exception('البيانات غير صالحة');
      }
      return SuperAdminStatsModel.fromJson(decoded['data'] as Map<String, dynamic>);
    } else {
      final decoded = jsonDecode(response.body) as Map<String, dynamic>;
      final error = decoded['error'] as String? ?? 'فشل في جلب إحصائيات المشرف العام';
      throw Exception(error);
    }
  }

  // English: Request a new WhatsApp QR connection.
  // Arabic: طلب اتصال واتساب جديد برمز استجابة سريع.
  Future<void> requestWhatsAppQr() async {
    final token = await _getToken();
    final response = await _apiService.requestWhatsAppQr(token);

    if (response.statusCode != 200) {
      final decoded = jsonDecode(response.body) as Map<String, dynamic>;
      final error = decoded['message'] as String? ?? 'فشل في طلب رمز الاستجابة السريعة';
      throw Exception(error);
    }
  }

  // English: Disconnect the active WhatsApp connection.
  // Arabic: قطع اتصال الواتساب النشط.
  Future<void> disconnectWhatsApp() async {
    final token = await _getToken();
    final response = await _apiService.disconnectWhatsApp(token);

    if (response.statusCode != 200) {
      final decoded = jsonDecode(response.body) as Map<String, dynamic>;
      final error = decoded['message'] as String? ?? 'فشل في قطع الاتصال';
      throw Exception(error);
    }
  }

  // English: Approve a pending company subscription.
  // Arabic: الموافقة على اشتراك شركة معلق.
  Future<void> approveBilling(int companyId) async {
    final token = await _getToken();
    final response = await _apiService.approveBilling(token, companyId);

    if (response.statusCode != 200) {
      final decoded = jsonDecode(response.body) as Map<String, dynamic>;
      final error = decoded['error'] as String? ?? 'فشل في الموافقة على الاشتراك';
      throw Exception(error);
    }
  }

  // English: Load connected Meta sessions.
  Future<List<MetaSessionModel>> getMetaSessions() async {
    final token = await _getToken();
    final response = await _apiService.getMetaSessions(token);

    if (response.statusCode == 200) {
      final decoded = jsonDecode(response.body) as Map<String, dynamic>;
      final list = decoded['data'] as List<dynamic>? ?? [];
      return list.map((item) => MetaSessionModel.fromJson(item as Map<String, dynamic>)).toList();
    } else {
      throw Exception('فشل في جلب جلسات ميتا المتصلة');
    }
  }

  // English: Connect a new Facebook Page or Instagram channel.
  Future<void> connectMetaSession(String channelType, String pageId, String pageName, String pageAccessToken) async {
    final token = await _getToken();
    final response = await _apiService.connectMetaSession(token, channelType, pageId, pageName, pageAccessToken);

    if (response.statusCode != 200) {
      final decoded = jsonDecode(response.body) as Map<String, dynamic>;
      final error = decoded['message'] as String? ?? 'فشل في ربط القناة';
      throw Exception(error);
    }
  }

  // English: Disconnect a Meta page or Instagram channel.
  Future<void> disconnectMetaSession(int sessionId) async {
    final token = await _getToken();
    final response = await _apiService.disconnectMetaSession(token, sessionId);

    if (response.statusCode != 200) {
      final decoded = jsonDecode(response.body) as Map<String, dynamic>;
      final error = decoded['message'] as String? ?? 'فشل في قطع اتصال القناة';
      throw Exception(error);
    }
  }
}
