import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../core/api/api_client_provider.dart';
import '../../../core/auth/auth_notifier.dart';

/// One row in the Chat Tab > Pembayaran sub-tab.
///
/// Mirrors the response of `GET /api/client/payment-sessions/pending`. A row
/// is either an initial-session payment (`isExtension == false`) — for which
/// mitra info is only present in the targeted "Curhat lagi" flow — or an
/// extension payment (`isExtension == true`) — mitra info resolved by the
/// backend via session_extensions → chat_sessions.
class PendingPaymentItem {
  final String id;
  final bool isExtension;
  final int amount;
  final int durationMinutes;
  final String mode;
  final DateTime createdAt;
  final DateTime expiresAt;
  final String? mitraId;
  final String? mitraDisplayName;

  const PendingPaymentItem({
    required this.id,
    required this.isExtension,
    required this.amount,
    required this.durationMinutes,
    required this.mode,
    required this.createdAt,
    required this.expiresAt,
    required this.mitraId,
    required this.mitraDisplayName,
  });

  factory PendingPaymentItem.fromJson(Map<String, dynamic> json) {
    return PendingPaymentItem(
      id: json['id'] as String,
      isExtension: json['is_extension'] as bool? ?? false,
      amount: switch (json['amount']) {
        num n => n.toInt(),
        String s => int.tryParse(s) ?? 0,
        _ => 0,
      },
      durationMinutes: switch (json['duration_minutes']) {
        num n => n.toInt(),
        String s => int.tryParse(s) ?? 0,
        _ => 0,
      },
      mode: json['mode'] as String? ?? 'chat',
      createdAt: DateTime.parse(json['created_at'] as String).toLocal(),
      expiresAt: DateTime.parse(json['expires_at'] as String).toLocal(),
      mitraId: json['mitra_id'] as String?,
      mitraDisplayName: json['mitra_display_name'] as String?,
    );
  }
}

class PendingPaymentsData {
  final List<PendingPaymentItem> items;
  final int total;
  const PendingPaymentsData({required this.items, required this.total});
  static const empty = PendingPaymentsData(items: [], total: 0);
}

/// Customer-scoped pending payment sessions. Returns `empty` when the caller
/// has no auth identity — keeps SHome1st + the chat tab from issuing a 401.
///
/// Drives both the Pembayaran sub-tab list and the bottom-nav red dot via the
/// `pendingPaymentsCountProvider` derivative below.
final pendingPaymentsProvider =
    FutureProvider<PendingPaymentsData>((ref) async {
  final customerId = ref.watch(authProvider.select((s) {
    final data = s.valueOrNull;
    return switch (data) {
      AuthAuthenticatedData d => d.profile['id'] as String?,
      AuthAnonymousData d => d.customerId,
      _ => null,
    };
  }));
  if (customerId == null) return PendingPaymentsData.empty;
  final api = ref.read(apiClientProvider);
  final response =
      await api.get('/api/client/payment-sessions/pending');
  final data = response['data'] as Map<String, dynamic>? ?? const {};
  final items = (data['items'] as List<dynamic>? ?? [])
      .cast<Map<String, dynamic>>()
      .map(PendingPaymentItem.fromJson)
      .toList();
  return PendingPaymentsData(
    items: items,
    total: switch (data['total']) {
      num n => n.toInt(),
      String s => int.tryParse(s) ?? items.length,
      _ => items.length,
    },
  );
});

/// Lightweight derived count — feeds the bottom-nav red dot + the Pembayaran
/// sub-tab pill badge. Returns 0 while the underlying provider is loading or
/// has errored, so the badge never flickers from a transient state.
final pendingPaymentsCountProvider = Provider<int>((ref) {
  final async = ref.watch(pendingPaymentsProvider);
  return async.valueOrNull?.total ?? 0;
});
