import 'package:flutter/material.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/transfer_record.dart';
import '../../../providers/transfer_provider.dart';
import '../../widgets/common/app_refresh_indicator.dart';

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

  @override
  ConsumerState<TransferHistoryScreen> createState() =>
      _TransferHistoryScreenState();
}

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

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

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

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

    if (state.isLoading && state.records.isEmpty) {
      return const Center(child: CircularProgressIndicator());
    }

    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)),
              ],
            ),
          ),
        ),
      );
    }

    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 TransferRecord record;

  String _walletName(BuildContext context, String type) {
    final l10n = AppLocalizations.of(context)!;
    switch (type) {
      case 'SPOT': return l10n.fundAccount;
      case 'SWAP': return l10n.futuresAccount;
      case 'FOLLOW': return l10n.copyAccount;
      case 'EXCHANGE': return l10n.exchangeAccount;
      default: return type;
    }
  }

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

    // 去除尾部零
    final amount = record.amount.replaceAll(RegExp(r'0+$'), '').replaceAll(RegExp(r'\.$'), '');

    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 14),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '${_walletName(context, record.source)} → ${_walletName(context, record.target)}',
                  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)),
              ],
            ),
          ),
          Text(
            '$amount ${record.unit}',
            style: const TextStyle(color: AppColors.rise, fontSize: 15, fontWeight: FontWeight.w600),
          ),
        ],
      ),
    );
  }
}
