import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../core/theme/halo_tokens.dart';
import '../providers/pending_payments_provider.dart';
import '../widgets/chat_row.dart';

/// Chat-Tab > pembayaran sub-tab.
///
/// Lists pending initial + extension payments. Row tap resumes the
/// waiting-payment screen for that payment session.
class PembayaranView extends ConsumerWidget {
  const PembayaranView({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final async = ref.watch(pendingPaymentsProvider);
    return RefreshIndicator(
      onRefresh: () => ref.refresh(pendingPaymentsProvider.future),
      color: HaloTokens.brand,
      child: async.when(
        loading: () => const _Loading(),
        error: (e, _) => _CenteredMessage(text: 'gagal memuat: $e'),
        data: (data) {
          if (data.items.isEmpty) {
            return const _CenteredMessage(
              text: 'belum ada pembayaran tertunda',
            );
          }
          return ListView.builder(
            padding: const EdgeInsets.symmetric(
              horizontal: HaloSpacing.s20,
              vertical: HaloSpacing.s12,
            ),
            itemCount: data.items.length,
            itemBuilder: (_, i) {
              final item = data.items[i];
              final name = item.mitraDisplayName ?? 'Bestie';
              return ChatRow(
                seed: name.codeUnits.fold<int>(0, (a, b) => a + b),
                name: name,
                preview: item.isExtension
                    ? 'menunggu pembayaran perpanjangan'
                    : 'menunggu pembayaran sesi',
                trailing: _relativeTime(item.createdAt),
                chips: [PaymentAmountChip(amount: item.amount)],
                isCall: item.mode == 'call',
                onTap: () => context.push('/payment/waiting/${item.id}'),
              );
            },
          );
        },
      ),
    );
  }
}

/// Loose "2 mnt lalu" formatter — enough for the row trailing label without
/// dragging in `intl`. Mirrors the Figma copy style.
String _relativeTime(DateTime when) {
  final delta = DateTime.now().difference(when);
  if (delta.inSeconds < 60) return 'baru aja';
  if (delta.inMinutes < 60) return '${delta.inMinutes} mnt lalu';
  if (delta.inHours < 24) return '${delta.inHours} jam lalu';
  if (delta.inDays < 7) return '${delta.inDays} hari lalu';
  return '${(delta.inDays / 7).floor()} mgg lalu';
}

class _Loading extends StatelessWidget {
  const _Loading();
  @override
  Widget build(BuildContext context) => const Center(
        child: CircularProgressIndicator(color: HaloTokens.brand),
      );
}

class _CenteredMessage extends StatelessWidget {
  final String text;
  const _CenteredMessage({required this.text});
  @override
  Widget build(BuildContext context) {
    return ListView(
      physics: const AlwaysScrollableScrollPhysics(),
      children: [
        Padding(
          padding: const EdgeInsets.symmetric(
            horizontal: HaloSpacing.s20,
            vertical: HaloSpacing.s64,
          ),
          child: Text(
            text,
            textAlign: TextAlign.center,
            style: const TextStyle(
              fontFamily: HaloTokens.fontBody,
              fontSize: 13,
              color: HaloTokens.inkMuted,
            ),
          ),
        ),
      ],
    );
  }
}
