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 TiXianListActivity）
class WithdrawalRecordPage extends ConsumerStatefulWidget {
  const WithdrawalRecordPage({super.key});

  @override
  ConsumerState<WithdrawalRecordPage> createState() =>
      _WithdrawalRecordPageState();
}

class _WithdrawalRecordPageState
    extends ConsumerState<WithdrawalRecordPage> {
  MultiState _state = MultiState.loading;
  List<WithdrawalRecord> _items = [];

  @override
  void initState() {
    super.initState();
    _load();
  }

  Future<void> _load() async {
    setState(() => _state = MultiState.loading);
    try {
      final BaseResponse<PageResult<dynamic>> resp =
          await ref.read(userApiProvider).withdrawalRecords();
      if (!mounted) return;
      if (!resp.isSuccess) {
        setState(() => _state = MultiState.error);
        return;
      }
      final list = (resp.data?.list as List?)
              ?.map((e) => WithdrawalRecord.fromJson(
                    e as Map<String, dynamic>,
                  ))
              .toList() ??
          const [];
      setState(() {
        _items = list;
        _state = list.isEmpty ? MultiState.empty : MultiState.success;
      });
    } catch (e) {
      if (mounted) setState(() => _state = MultiState.error);
    }
  }

  @override
  Widget build(BuildContext context) {
    final fmt = DateFormat('yyyy-MM-dd HH:mm');
    return Scaffold(
      appBar: AppBar(title: const Text('提现记录')),
      body: RefreshIndicator(
        onRefresh: _load,
        child: MultiStateView(
          state: _state,
          emptyText: '暂无提现记录',
          onRetry: _load,
          child: ListView.separated(
            padding: const EdgeInsets.all(12),
            itemCount: _items.length,
            separatorBuilder: (_, __) => const SizedBox(height: 8),
            itemBuilder: (ctx, i) {
              final w = _items[i];
              Color color;
              String status;
              switch (w.status) {
                case 'success':
                  color = Colors.green;
                  status = '已到账';
                  break;
                case 'failed':
                  color = Colors.red;
                  status = '已失败';
                  break;
                default:
                  color = Colors.orange;
                  status = '审核中';
              }
              return Material(
                color: Colors.white,
                borderRadius: BorderRadius.circular(8),
                child: ListTile(
                  leading: CircleAvatar(
                    backgroundColor: color.withValues(alpha: 0.1),
                    child: Icon(Icons.account_balance_wallet, color: color),
                  ),
                  title: Text(
                    '¥${w.amount.toStringAsFixed(2)}',
                    style: const TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 16,
                    ),
                  ),
                  subtitle: Text(
                    '${w.bankAccount ?? "—"}\n${fmt.format(w.createdAt)}',
                    style: const TextStyle(fontSize: 12),
                  ),
                  isThreeLine: true,
                  trailing: Container(
                    padding: const EdgeInsets.symmetric(
                      horizontal: 6,
                      vertical: 2,
                    ),
                    decoration: BoxDecoration(
                      color: color.withValues(alpha: 0.1),
                      borderRadius: BorderRadius.circular(4),
                    ),
                    child: Text(
                      status,
                      style: TextStyle(color: color, fontSize: 11),
                    ),
                  ),
                ),
              );
            },
          ),
        ),
      ),
    );
  }
}
