// lib/features/events/services/events_service.dart
import 'package:intl/intl.dart';
import '../../../core/api/api_client.dart';
import '../../../core/api/api_endpoints.dart';
import '../models/event_models.dart';

class EventsService {
  final ApiClient _api = ApiClient();

  /// Get event types (POST to /events/type-list/)
  Future<List<EventTypeModel>> getEventTypes() async {
    final res = await _api.post(ApiEndpoints.eventTypes);
    final list = <EventTypeModel>[];
    final data = res['event_types'] ?? res['event_types'] ?? res;
    if (data is List) {
      for (final e in data) {
        if (e is Map<String, dynamic>) list.add(EventTypeModel.fromJson(e));
      }
    } else if (res['event_types'] is List) {
      for (final e in res['event_types']) {
        list.add(EventTypeModel.fromJson(Map<String, dynamic>.from(e)));
      }
    }
    return list;
  }

  /// Get events filtered by pincode (POST to /events/pincode-events/)
  /// Use pincode='all' to fetch all events.
  Future<List<EventModel>> getEventsByPincode(String pincode) async {
    final res = await _api.post(ApiEndpoints.eventsByPincode, body: {'pincode': pincode});
    final list = <EventModel>[];
    final events = res['events'] ?? res['data'] ?? [];
    if (events is List) {
      for (final e in events) {
        if (e is Map<String, dynamic>) list.add(EventModel.fromJson(Map<String, dynamic>.from(e)));
      }
    }
    return list;
  }

  /// Event details
  Future<EventModel> getEventDetails(int eventId) async {
    final res = await _api.post(ApiEndpoints.eventDetails, body: {'event_id': eventId});
    return EventModel.fromJson(Map<String, dynamic>.from(res));
  }

  /// Events by month and year for calendar (POST to /events/events-by-month-year/)
  /// Accepts month string and year int.
  /// Returns Map with 'dates' (list of YYYY-MM-DD) and 'date_events' (list with counts).
  Future<Map<String, dynamic>> getEventsByMonthYear(String month, int year) async {
    final res = await _api.post(ApiEndpoints.eventsByMonth, body: {'month': month, 'year': year});
    // expected keys: dates, total_number_of_events, date_events
    return res;
  }

  /// Convenience: get events for a specific date (YYYY-MM-DD)
  Future<List<EventModel>> getEventsForDate(String date) async {
    // Simplest approach: hit pincode-events with filter or hit events-by-month-year and then
    // query event-details for events of that date. Assuming backend doesn't provide direct endpoint,
    // we'll call eventsByPincode('all') and filter locally by date — acceptable for demo/small datasets.
    final all = await getEventsByPincode('all');
    return all.where((e) {
      try {
        return e.startDate == date || e.endDate == date || (DateTime.parse(e.startDate).isBefore(DateTime.parse(date)) && DateTime.parse(e.endDate).isAfter(DateTime.parse(date)));
      } catch (_) {
        return false;
      }
    }).toList();
  }
}
