import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';

import '../../../core/l10n/app_localizations.dart';
import '../../../core/theme/app_colors.dart';
import '../../../data/models/asset/recharge_record.dart';
import '../../../providers/deposit_provider.dart';
import '../../widgets/common/app_refresh_indicator.dart';

class DepositHistoryScreen extends ConsumerStatefulWidget {
  const DepositHistoryScreen({super.key});

  @override
  ConsumerState<DepositHistoryScreen> createState() =>
      _DepositHistoryScreenState();
}

class _DepositHistoryScreenState extends ConsumerState<DepositHistoryScreen> {
  @override
  void initState() {
    super.initState();
    // 进入页面时自动刷新一次
    Future.microtask(() {
      ref.read(rechargeHistoryProvider.notifier).refresh();
    });
  }

  @override
  Widget build(BuildContext context) {
    final state = ref.watch(rechargeHistoryProvider);
    final notifier = ref.read(rechargeHistoryProvider.notifier);

    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: const Icon(Icons.chevron_left, size: 28),
          onPressed: () => context.pop(),
        ),
        title: Text(AppLocalizations.of(context)!.depositRecord, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w600)),
        centerTitle: true,
      ),
      body: _buildBody(context, state, notifier),
    );
  }

  Widget _buildBody(BuildContext context, RechargeHistoryState state, RechargeHistoryNotifier notifier) {
    final cs = Theme.of(context).colorScheme;

    // Loading（首次）
    if (state.isLoading && state.records.isEmpty) {
      return const Center(child: CircularProgressIndicator());
    }

    // Error（首次）
    if (state.errorMessage != null && state.records.isEmpty) {
      return AppRefreshIndicator(
        onRefresh: notifier.refresh,
        child: SingleChildScrollView(
          physics: const AlwaysScrollableScrollPhysics(),
          child: Center(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(state.errorMessage!, style: TextStyle(color: cs.onSurface.withAlpha(153))),
                const SizedBox(height: 16),
                ElevatedButton(onPressed: notifier.refresh, child: Text(AppLocalizations.of(context)!.retry)),
              ],
            ),
          ),
        ),
      );
    }

    // Empty - with RefreshIndicator
    if (state.records.isEmpty) {
      return AppRefreshIndicator(
        onRefresh: notifier.refresh,
        child: SingleChildScrollView(
          physics: const AlwaysScrollableScrollPhysics(),
          child: Center(
            child: Padding(
              padding: const EdgeInsets.symmetric(vertical: 100),
              child: Text(AppLocalizations.of(context)!.noRecord, style: TextStyle(color: cs.onSurface.withAlpha(120), fontSize: 15)),
            ),
          ),
        ),
      );
    }

    return AppRefreshIndicator(
      onRefresh: notifier.refresh,
      child: NotificationListener<ScrollNotification>(
        onNotification: (notification) {
          if (notification is ScrollEndNotification &&
              notification.metrics.pixels >= notification.metrics.maxScrollExtent - 100) {
            notifier.loadMore();
          }
          return false;
        },
        child: ListView.separated(
          padding: const EdgeInsets.fromLTRB(16, 16, 16, 32),
          itemCount: state.records.length + (state.hasMore ? 1 : 0),
          separatorBuilder: (_, __) => Divider(height: 1, color: cs.outline.withAlpha(30)),
          itemBuilder: (_, i) {
            if (i >= state.records.length) {
              return const Padding(
                padding: EdgeInsets.symmetric(vertical: 16),
                child: Center(child: CircularProgressIndicator(strokeWidth: 2)),
              );
            }
            return _RecordTile(record: state.records[i]);
          },
        ),
      ),
    );
  }
}

// ── 充值记录行 ──────────────────────────────────────────────────

class _RecordTile extends StatelessWidget {
  const _RecordTile({required this.record});
  final RechargeRecord record;

  @override
  Widget build(BuildContext context) {
    final cs = Theme.of(context).colorScheme;

    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        context.push('/asset/deposit/detail', extra: record);
      },
      child: Padding(
        padding: const EdgeInsets.symmetric(vertical: 14),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 左侧：标题 + 时间
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    'USDT ${AppLocalizations.of(context)!.recharge}',
                    style: TextStyle(color: cs.onSurface, fontSize: 15, fontWeight: FontWeight.w600),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    record.createTime,
                    style: TextStyle(color: cs.onSurface.withAlpha(120), fontSize: 12),
                  ),
                  if (record.txId.isNotEmpty) ...[
                    const SizedBox(height: 4),
                    GestureDetector(
                      onTap: () {
                        Clipboard.setData(ClipboardData(text: record.txId));
                        ScaffoldMessenger.of(context).showSnackBar(
                          SnackBar(content: Text(AppLocalizations.of(context)!.hashCopied), duration: const Duration(seconds: 1)),
                        );
                      },
                      child: Text(
                        'TX: ${_truncate(record.txId)}',
                        style: TextStyle(color: cs.onSurface.withAlpha(100), fontSize: 11),
                      ),
                    ),
                  ],
                ],
              ),
            ),
            // 右侧：金额
            Text(
              '+${record.amount}',
              style: const TextStyle(color: AppColors.rise, fontSize: 15, fontWeight: FontWeight.w600),
            ),
          ],
        ),
      ),
    );
  }

  String _truncate(String s) {
    if (s.length <= 16) return s;
    return '${s.substring(0, 8)}...${s.substring(s.length - 8)}';
  }
}
