import 'package:dio/dio.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'api_client.dart';

final apiServiceProvider = Provider<ApiService>((ref) {
  return ApiService(ref.watch(dioProvider));
});

class ApiService {
  final Dio _dio;

  ApiService(this._dio);

  // === Auth ===
  Future<Map<String, dynamic>> requestOtp(String phone) async {
    final res = await _dio.post('/auth/otp/request', data: {'phone': phone});
    return res.data;
  }

  Future<Map<String, dynamic>> verifyOtp(String phone, String otp) async {
    final res = await _dio.post(
      '/auth/otp/verify',
      data: {'phone': phone, 'otp': otp},
    );
    return res.data;
  }

  Future<void> logout() async {
    await _dio.post('/auth/logout');
  }

  Future<Map<String, dynamic>> getMe() async {
    final res = await _dio.get('/auth/me');
    return res.data;
  }

  // === Config ===
  Future<Map<String, dynamic>> getAppConfig() async {
    final res = await _dio.get('/app/config');
    return res.data;
  }

  // === Dashboard ===
  Future<Map<String, dynamic>> getDashboard() async {
    final res = await _dio.get('/dashboard');
    return res.data['data'];
  }

  // === Participants ===
  Future<List<dynamic>> getChildren() async {
    final res = await _dio.get('/guardian/children');
    return res.data['data'];
  }

  Future<Map<String, dynamic>> getParticipant(String uuid) async {
    final res = await _dio.get('/participants/$uuid');
    return res.data['data'];
  }

  Future<Map<String, dynamic>> getParticipantSummary(String uuid) async {
    final res = await _dio.get('/participants/$uuid/summary');
    return res.data['data'];
  }

  Future<List<dynamic>> getSchedule(String uuid) async {
    final res = await _dio.get('/participants/$uuid/schedule');
    return res.data['data'];
  }

  Future<Map<String, dynamic>> getAttendance(
    String uuid, {
    int page = 1,
  }) async {
    final res = await _dio.get(
      '/participants/$uuid/attendance',
      queryParameters: {'page': page},
    );
    return res.data;
  }

  Future<Map<String, dynamic>> getInvoices(String uuid, {int page = 1}) async {
    final res = await _dio.get(
      '/participants/$uuid/invoices',
      queryParameters: {'page': page},
    );
    return res.data;
  }

  Future<List<dynamic>> getEnrollments(String uuid) async {
    final res = await _dio.get('/participants/$uuid/enrollments');
    return res.data['data'];
  }

  Future<Map<String, dynamic>> getDocuments(String uuid) async {
    final res = await _dio.get('/participants/$uuid/documents');
    return res.data;
  }

  Future<Map<String, dynamic>> getWallet(String uuid) async {
    final res = await _dio.get('/participants/$uuid/wallet');
    return res.data['data'];
  }

  Future<Map<String, dynamic>> getWalletTransactions(
    String uuid, {
    int page = 1,
  }) async {
    final res = await _dio.get(
      '/participants/$uuid/wallet/transactions',
      queryParameters: {'page': page},
    );
    return res.data;
  }

  Future<List<dynamic>> getInstallments(String uuid) async {
    final res = await _dio.get('/participants/$uuid/installments');
    return res.data['data'];
  }

  Future<List<dynamic>> getEvaluations(String uuid) async {
    final res = await _dio.get('/participants/$uuid/evaluations');
    return res.data['data'];
  }

  Future<Map<String, dynamic>> getEvaluationDetail(
    String uuid,
    String evalUuid,
  ) async {
    final res = await _dio.get('/participants/$uuid/evaluations/$evalUuid');
    return res.data['data'];
  }

  // === Notifications ===
  Future<Map<String, dynamic>> getNotifications({int page = 1}) async {
    final res = await _dio.get(
      '/notifications',
      queryParameters: {'page': page},
    );
    return res.data;
  }

  Future<void> markNotificationRead(int id) async {
    await _dio.patch('/notifications/$id/read');
  }

  Future<void> markAllNotificationsRead() async {
    await _dio.post('/notifications/read-all');
  }

  Future<Map<String, dynamic>> getNotificationPreferences() async {
    final res = await _dio.get('/notifications/preferences');
    return res.data;
  }

  Future<void> updateNotificationPreferences(
    List<Map<String, dynamic>> prefs,
  ) async {
    await _dio.post('/notifications/preferences', data: {'preferences': prefs});
  }

  // === Profile ===
  Future<Map<String, dynamic>> getProfile() async {
    final res = await _dio.get('/profile');
    return res.data['data'];
  }

  Future<Map<String, dynamic>> updateProfile(Map<String, dynamic> data) async {
    final res = await _dio.patch('/profile', data: data);
    return res.data;
  }

  // === Shop ===
  Future<List<dynamic>> getProducts() async {
    final res = await _dio.get('/products');
    return res.data['data'];
  }

  Future<Map<String, dynamic>> createOrder(Map<String, dynamic> data) async {
    final res = await _dio.post('/orders/create', data: data);
    return res.data;
  }

  Future<Map<String, dynamic>> getOrders({int page = 1}) async {
    final res = await _dio.get('/orders', queryParameters: {'page': page});
    return res.data;
  }

  // === Payments ===
  Future<Map<String, dynamic>> initiatePayment(String invoiceUuid) async {
    final res = await _dio.post(
      '/payments/initiate',
      data: {'invoice_uuid': invoiceUuid},
    );
    return res.data;
  }

  Future<Map<String, dynamic>> getInvoiceDetail(String uuid) async {
    final res = await _dio.get('/invoices/$uuid');
    return res.data['data'];
  }

  Future<Map<String, dynamic>> getPaymentReceipt(String uuid) async {
    final res = await _dio.get('/payments/$uuid/receipt');
    return res.data['data'];
  }

  // === Events ===
  Future<Map<String, dynamic>> getEvents({int page = 1}) async {
    final res = await _dio.get(
      '/academy/events',
      queryParameters: {'page': page},
    );
    return res.data;
  }

  Future<Map<String, dynamic>> getEventDetail(String uuid) async {
    final res = await _dio.get('/academy/events/$uuid');
    return res.data['data'];
  }

  Future<Map<String, dynamic>> registerForEvent(
    String uuid,
    String participantUuid, {
    String? notes,
  }) async {
    final res = await _dio.post(
      '/events/$uuid/register',
      data: {'participant_uuid': participantUuid, 'notes': ?notes},
    );
    return res.data;
  }

  Future<List<dynamic>> getMyRegistrations() async {
    final res = await _dio.get('/events/my-registrations');
    return res.data['data'];
  }

  // === Service Requests ===
  Future<Map<String, dynamic>> createServiceRequest(
    Map<String, dynamic> data,
  ) async {
    final res = await _dio.post('/service-requests', data: data);
    return res.data;
  }

  Future<List<dynamic>> getServiceRequests() async {
    final res = await _dio.get('/service-requests');
    return res.data['data'];
  }

  Future<void> cancelServiceRequest(String uuid) async {
    await _dio.post('/service-requests/$uuid/cancel');
  }

  // === Absences ===
  Future<void> reportAbsence(Map<String, dynamic> data) async {
    await _dio.post('/absences/report', data: data);
  }

  // === Messages ===
  Future<Map<String, dynamic>> sendMessage(Map<String, dynamic> data) async {
    final res = await _dio.post('/messages/send', data: data);
    return res.data;
  }

  Future<Map<String, dynamic>> getMessages({int page = 1}) async {
    final res = await _dio.get('/messages', queryParameters: {'page': page});
    return res.data;
  }

  // === Registration ===
  Future<Map<String, dynamic>> preRegister({
    required String guardianNameAr,
    String? guardianName,
    required String phone,
    String? email,
    required String participantName,
    required int participantAge,
    required String gender,
  }) async {
    final res = await _dio.post(
      '/register/pre-register',
      data: {
        'guardian_name_ar': guardianNameAr,
        if (guardianName != null && guardianName.isNotEmpty)
          'guardian_name': guardianName,
        'phone': phone,
        if (email != null && email.isNotEmpty) 'email': email,
        'participant_name': participantName,
        'participant_age': participantAge,
        'gender': gender,
      },
    );
    return res.data;
  }

  // === Academy (public) ===
  Future<Map<String, dynamic>> getNews({int page = 1}) async {
    final res = await _dio.get(
      '/academy/news',
      queryParameters: {'page': page},
    );
    return res.data;
  }

  Future<Map<String, dynamic>> getNewsDetail(String uuid) async {
    final res = await _dio.get('/academy/news/$uuid');
    return res.data['data'];
  }

  Future<List<dynamic>> getPrograms() async {
    final res = await _dio.get('/academy/programs');
    return res.data['data'];
  }

  Future<List<dynamic>> getBranches() async {
    final res = await _dio.get('/branches');
    return res.data['data'];
  }

  Future<Map<String, dynamic>> getGallery({int page = 1}) async {
    final res = await _dio.get(
      '/academy/gallery',
      queryParameters: {'page': page},
    );
    return res.data;
  }

  // === Devices ===
  Future<void> registerDevice(
    String token,
    String platform, {
    String? deviceName,
    String? appVersion,
  }) async {
    await _dio.post(
      '/devices/register',
      data: {
        'token': token,
        'platform': platform,
        'device_name': ?deviceName,
        'app_version': ?appVersion,
      },
    );
  }

  Future<void> unregisterDevice(String token) async {
    await _dio.delete('/devices/$token');
  }

  // === Push ===
  Future<Map<String, dynamic>> getBadgeCount() async {
    final res = await _dio.get('/push/badge');
    return res.data;
  }

  Future<void> trackPushEvent(List<Map<String, dynamic>> events) async {
    await _dio.post('/push/track', data: {'events': events});
  }
}
