import 'dart:convert';

import 'package:http/http.dart' as http;
import 'package:intl/intl.dart';

import '../../core/hijri_date.dart';

class HijriCalendarService {
  HijriCalendarService._({http.Client? client})
      : _client = client ?? http.Client();

  static final HijriCalendarService instance = HijriCalendarService._();
  static const String _baseUrl = 'https://api.myquran.com/v3/cal/hijr';

  final http.Client _client;
  final Map<String, String> _cache = {};

  Future<String> getHijriLabel(DateTime date) async {
    final dateOnly = DateTime(date.year, date.month, date.day);
    final dateKey = DateFormat('yyyy-MM-dd').format(dateOnly);
    final cached = _cache[dateKey];
    if (cached != null) return cached;

    try {
      final response = await _client.get(Uri.parse('$_baseUrl/$dateKey'));
      if (response.statusCode == 200) {
        final payload = json.decode(response.body) as Map<String, dynamic>;
        final label = parseHijriLabel(payload);
        if (label != null) {
          _cache[dateKey] = label;
          return label;
        }
      }
    } catch (_) {
      // Keep UI usable when the device is offline.
    }

    final fallback = HijriDateFormatter.format(dateOnly);
    _cache[dateKey] = fallback;
    return fallback;
  }

  static String? parseHijriLabel(Map<String, dynamic> payload) {
    if (payload['status'] != true) return null;

    final data = payload['data'];
    if (data is! Map) return null;

    final hijr = data['hijr'];
    if (hijr is! Map) return null;

    final today = hijr['today']?.toString().trim();
    if (today != null && today.isNotEmpty) {
      final parts = today.split(',');
      return parts.length > 1 ? parts.last.trim() : today;
    }

    final day = hijr['day'];
    final monthName = hijr['monthName']?.toString().trim();
    final year = hijr['year'];

    if (day != null && monthName != null && monthName.isNotEmpty && year != null) {
      return '$day $monthName $year H';
    }

    return null;
  }
}
