import 'package:autosos_flutter/model/base_response.dart';
import 'package:autosos_flutter/model/payment.dart';
import 'package:autosos_flutter/provider/providers.dart';
import 'package:autosos_flutter/widget/multi_state_view.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:intl/intl.dart';

/// 金额明细（对应 Android AmountListActivity）
class AmountListPage extends ConsumerStatefulWidget {
  const AmountListPage({super.key});

  @override
  ConsumerState<AmountListPage> createState() => _AmountListPageState();
}

class _AmountListPageState extends ConsumerState<AmountListPage> {
  MultiState _state = MultiState.loading;
  List<AmountItem> _items = [];
  int _page = 1;
  bool _hasMore = true;
  bool _loadingMore = false;
  final _scroll = ScrollController();

  @override
  void initState() {
    super.initState();
    _load(reset: true);
    _scroll.addListener(() {
      if (_scroll.position.pixels >=
          _scroll.position.maxScrollExtent - 200) {
        _load();
      }
    });
  }

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

  Future<void> _load({bool reset = false}) async {
    if (reset) {
      _page = 1;
      _hasMore = true;
      _items = [];
      setState(() => _state = MultiState.loading);
    }
    if (!_hasMore || _loadingMore) return;
    _loadingMore = true;
    try {
      final BaseResponse<PageResult<dynamic>> resp =
          await ref.read(userApiProvider).amountList(
                page: _page,
                size: 20,
              );
      if (!mounted) return;
      if (!resp.isSuccess) {
        if (reset) setState(() => _state = MultiState.error);
        return;
      }
      final list = (resp.data?.list as List?)
              ?.map((e) => AmountItem.fromJson(
                    e as Map<String, dynamic>,
                  ))
              .toList() ??
          const [];
      _items.addAll(list);
      _hasMore = (resp.data?.hasMore ?? false) && list.length >= 20;
      _page++;
      setState(() {
        _state = _items.isEmpty ? MultiState.empty : MultiState.success;
      });
    } catch (e) {
      if (mounted && reset) setState(() => _state = MultiState.error);
    } finally {
      _loadingMore = false;
    }
  }

  @override
  Widget build(BuildContext context) {
    final fmt = DateFormat('yyyy-MM-dd HH:mm');
    return Scaffold(
      appBar: AppBar(title: const Text('金额明细')),
      body: RefreshIndicator(
        onRefresh: () => _load(reset: true),
        child: MultiStateView(
          state: _state,
          emptyText: '暂无明细',
          onRetry: () => _load(reset: true),
          child: ListView.separated(
            controller: _scroll,
            padding: const EdgeInsets.all(12),
            itemCount: _items.length + (_hasMore ? 1 : 0),
            separatorBuilder: (_, __) => const SizedBox(height: 8),
            itemBuilder: (ctx, i) {
              if (i >= _items.length) {
                return const Padding(
                  padding: EdgeInsets.all(16),
                  child: Center(
                    child: CircularProgressIndicator(strokeWidth: 2),
                  ),
                );
              }
              final it = _items[i];
              final isIncome = it.type == 'income';
              return Material(
                color: Colors.white,
                borderRadius: BorderRadius.circular(8),
                child: ListTile(
                  leading: CircleAvatar(
                    backgroundColor:
                        (isIncome ? Colors.green : Colors.red).withValues(alpha: 0.1),
                    child: Icon(
                      isIncome ? Icons.add : Icons.remove,
                      color: isIncome ? Colors.green : Colors.red,
                    ),
                  ),
                  title: Text(it.title),
                  subtitle: Text(
                    '${it.orderNo ?? "—"}\n${fmt.format(it.createdAt)}',
                    style: const TextStyle(fontSize: 12),
                  ),
                  isThreeLine: true,
                  trailing: Text(
                    '${isIncome ? "+" : "-"}¥${it.amount.toStringAsFixed(2)}',
                    style: TextStyle(
                      color: isIncome ? Colors.green : Colors.red,
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              );
            },
          ),
        ),
      ),
    );
  }
}
