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

import '../../../core/l10n/app_localizations.dart';
import '../../../core/network/dio_client.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/utils/number_format.dart';
import '../../../data/services/spot_service.dart';

/// 资金流水页
///
/// 支持按币种 + 交易类型筛选，时间范围筛选，分页加载
class SpotAccountRecordsScreen extends ConsumerStatefulWidget {
  const SpotAccountRecordsScreen({super.key, this.initialSymbol});
  final String? initialSymbol;

  @override
  ConsumerState<SpotAccountRecordsScreen> createState() =>
      _SpotAccountRecordsScreenState();
}

class _SpotAccountRecordsScreenState
    extends ConsumerState<SpotAccountRecordsScreen> {
  final _scroll = ScrollController();
  final List<Map<String, dynamic>> _records = [];

  // 筛选状态
  String? _filterSymbol;
  int? _filterType;
  int _page = 1;
  bool _hasMore = true;
  bool _loading = false;
  bool _initialLoading = true;

  @override
  void initState() {
    super.initState();
    _filterSymbol = widget.initialSymbol;
    _scroll.addListener(_onScroll);
    _refresh();
  }

  @override
  void dispose() {
    _scroll.dispose();
    super.dispose();
  }

  void _onScroll() {
    if (_scroll.position.pixels >= _scroll.position.maxScrollExtent - 200) {
      _loadMore();
    }
  }

  Future<void> _refresh() async {
    setState(() {
      _loading = true;
      _page = 1;
      _hasMore = true;
      _records.clear();
    });
    await _fetch();
    if (mounted) setState(() => _initialLoading = false);
  }

  Future<void> _loadMore() async {
    if (_loading || !_hasMore) return;
    setState(() => _loading = true);
    _page++;
    await _fetch();
  }

  Future<void> _fetch() async {
    final svc = SpotService(ref.read(dioClientProvider));
    try {
      final data = await svc.getAccountRecords(
        symbol: _filterSymbol?.isNotEmpty == true ? _filterSymbol : null,
        type: _filterType,
        page: _page,
        size: 20,
      );
      final records = data['records'];
      final total = data['total'] as int? ?? 0;
      if (records is List && mounted) {
        setState(() {
          _records.addAll(records.whereType<Map<String, dynamic>>());
          _hasMore = total > _records.length;
          _loading = false;
        });
      } else {
        if (mounted) setState(() => _loading = false);
      }
    } catch (_) {
      if (mounted) setState(() => _loading = false);
    }
  }

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

    return Scaffold(
      appBar: AppBar(
        title: Text(l10n.accountRecords),
        elevation: 0,
      ),
      body: Column(
        children: [
          // 筛选行
          _FilterBar(
            l10n: l10n,
            selectedType: _filterType,
            onTypeChanged: (t) {
              setState(() => _filterType = t);
              _refresh();
            },
          ),
          // 列表
          Expanded(
            child: _initialLoading
                ? const Center(child: CircularProgressIndicator())
                : _records.isEmpty
                    ? Center(
                        child: Text(l10n.noMoreData,
                            style: TextStyle(
                                color: cs.onSurface.withAlpha(140),
                                fontSize: 14)),
                      )
                    : RefreshIndicator(
                        onRefresh: _refresh,
                        child: ListView.builder(
                          controller: _scroll,
                          itemCount: _records.length + 1,
                          itemBuilder: (_, i) {
                            if (i == _records.length) {
                              return _loadingFooter(cs);
                            }
                            return _RecordRow(l10n: l10n, record: _records[i]);
                          },
                        ),
                      ),
          ),
        ],
      ),
    );
  }

  Widget _loadingFooter(ColorScheme cs) {
    if (_loading) {
      return const Padding(
        padding: EdgeInsets.all(16),
        child: Center(child: CircularProgressIndicator()),
      );
    }
    if (!_hasMore && _records.isNotEmpty) {
      return Padding(
        padding: const EdgeInsets.all(16),
        child: Center(
          child: Text(
            AppLocalizations.of(context)!.noMoreData,
            style: TextStyle(color: cs.onSurface.withAlpha(120), fontSize: 13),
          ),
        ),
      );
    }
    return const SizedBox.shrink();
  }
}

// ── 筛选栏 ──────────────────────────────────────────────────────────────
class _FilterBar extends StatelessWidget {
  const _FilterBar({
    required this.l10n,
    required this.selectedType,
    required this.onTypeChanged,
  });
  final AppLocalizations l10n;
  final int? selectedType;
  final ValueChanged<int?> onTypeChanged;

  List<MapEntry<int?, String>> get _options => [
        MapEntry(null, l10n.allLabel),
        MapEntry(5, l10n.spotAccountRecordFilterTrade),
        MapEntry(12, l10n.fee),
        MapEntry(1, l10n.transferIn),
        MapEntry(2, l10n.transferOut),
      ];

  @override
  Widget build(BuildContext context) {
    final cs = Theme.of(context).colorScheme;
    final options = _options;
    return Container(
      height: 42,
      color: cs.surface,
      child: ListView(
        scrollDirection: Axis.horizontal,
        padding: const EdgeInsets.symmetric(horizontal: 12),
        children: options.map((e) {
          final active = selectedType == e.key;
          return Padding(
            padding: const EdgeInsets.only(right: 8, top: 8, bottom: 8),
            child: GestureDetector(
              onTap: () => onTypeChanged(e.key),
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 12),
                decoration: BoxDecoration(
                  color: active
                      ? AppColors.brand.withAlpha(30)
                      : cs.surface,
                  border: Border.all(
                    color: active ? AppColors.brand : cs.outline.withAlpha(80),
                    width: active ? 1.2 : 0.8,
                  ),
                  borderRadius: BorderRadius.circular(14),
                ),
                alignment: Alignment.center,
                child: Text(
                  e.value,
                  style: TextStyle(
                    color: active ? AppColors.brand : cs.onSurface.withAlpha(180),
                    fontSize: 12,
                    fontWeight: active ? FontWeight.w600 : FontWeight.w400,
                  ),
                ),
              ),
            ),
          );
        }).toList(),
      ),
    );
  }
}

// ── 流水行 ──────────────────────────────────────────────────────────────
class _RecordRow extends StatelessWidget {
  const _RecordRow({required this.l10n, required this.record});
  final AppLocalizations l10n;
  final Map<String, dynamic> record;

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

    final type = record['type'] as int? ?? 0;
    final operateType = record['operateType'] as int? ?? 0;
    final amount = _toDouble(record['amount']);
    final symbol = (record['symbol'] as String? ?? '').toUpperCase();
    final remark = record['remark'] as String? ?? '';
    final ctimeRaw = record['ctime'];
    final timeStr = _formatTime(ctimeRaw);

    final label = _resolveLabel(l10n, type, operateType);
    final isPositive = operateType == 1;
    final amountColor = isPositive ? AppColors.rise : AppColors.fall;
    final amountSign = isPositive ? '+' : '-';

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
      decoration: BoxDecoration(
        border: Border(
          bottom: BorderSide(color: cs.outline.withAlpha(40), width: 0.6),
        ),
      ),
      child: Row(
        children: [
          // 左侧：类型 + 备注 + 时间
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(label,
                    style: TextStyle(
                      color: cs.onSurface,
                      fontSize: 14,
                      fontWeight: FontWeight.w500,
                    )),
                if (remark.isNotEmpty) ...[
                  const SizedBox(height: 2),
                  Text(remark,
                      style: TextStyle(
                          color: cs.onSurface.withAlpha(140), fontSize: 12)),
                ],
                const SizedBox(height: 2),
                Text(timeStr,
                    style: TextStyle(
                        color: cs.onSurface.withAlpha(120), fontSize: 11)),
              ],
            ),
          ),
          // 右侧：金额 + 币种
          Column(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              Text(
                '$amountSign${formatAmount(amount, decimals: 6)}',
                style: TextStyle(
                  color: amountColor,
                  fontSize: 14,
                  fontWeight: FontWeight.w600,
                  fontFeatures: const [FontFeature.tabularFigures()],
                ),
              ),
              Text(symbol,
                  style: TextStyle(
                      color: cs.onSurface.withAlpha(140), fontSize: 11)),
            ],
          ),
        ],
      ),
    );
  }

  String _resolveLabel(AppLocalizations l10n, int type, int operateType) {
    if (type == 5) {
      return operateType == 1
          ? l10n.spotAccountRecordTradeBuy
          : l10n.spotAccountRecordTradeSell;
    }
    return switch (type) {
      1 => l10n.transferIn,
      2 => l10n.transferOut,
      3 => l10n.spotAccountRecordTypeOrderFreeze,
      4 => l10n.spotAccountRecordTypeOrderUnfreeze,
      12 => l10n.fee,
      _ => l10n.unknown,
    };
  }

  static String _formatTime(dynamic raw) {
    if (raw == null) return '';
    DateTime? dt;
    if (raw is String) {
      dt = DateTime.tryParse(raw)?.toLocal();
    } else if (raw is int && raw > 0) {
      dt = DateTime.fromMillisecondsSinceEpoch(
        raw > 9999999999 ? raw : raw * 1000,
      ).toLocal();
    }
    if (dt == null) return '';
    return '${dt.year}-${_p(dt.month)}-${_p(dt.day)} ${_p(dt.hour)}:${_p(dt.minute)}';
  }

  static String _p(int n) => n.toString().padLeft(2, '0');

  static double _toDouble(dynamic v) {
    if (v == null) return 0;
    if (v is num) return v.toDouble();
    return double.tryParse(v.toString()) ?? 0;
  }
}
