import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:intl/intl.dart';
import '../../../core/constants/app_colors.dart';
import '../../../core/utils/format_utils.dart';
import '../../../data/models/p2p_transfer_model.dart';
import '../../providers/transfer_providers.dart';
import '../../providers/user_providers.dart';

/// P2P转账记录页面
/// [filterDirection] - 过滤方向: 'send' 只显示转出, 'receive' 只显示转入, null 显示全部
class P2pTransferRecordsPage extends ConsumerWidget {
  final String? filterDirection;

  const P2pTransferRecordsPage({super.key, this.filterDirection});

  static const Color _orange = Color(0xFFFF6B00);
  static const Color _green = Color(0xFF10B981);
  static const Color _red = Color(0xFFEF4444);
  static const Color _grayText = Color(0xFF6B7280);
  static const Color _darkText = Color(0xFF1F2937);
  static const Color _bgGray = Color(0xFFF3F4F6);

  String get _title {
    switch (filterDirection) {
      case 'send':
        return '转出记录';
      case 'receive':
        return '转入记录';
      default:
        return '转账记录';
    }
  }

  String get _emptyText {
    switch (filterDirection) {
      case 'send':
        return '暂无转出记录';
      case 'receive':
        return '暂无转入记录';
      default:
        return '暂无转账记录';
    }
  }

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final user = ref.watch(userNotifierProvider);
    final accountSequence = user.accountSequence ?? '';
    final recordsAsync = ref.watch(p2pTransferHistoryProvider(accountSequence));

    return Scaffold(
      backgroundColor: _bgGray,
      appBar: AppBar(
        title: Text(
          _title,
          style: const TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
            color: _darkText,
          ),
        ),
        centerTitle: true,
        backgroundColor: Colors.white,
        elevation: 0,
        iconTheme: const IconThemeData(color: _darkText),
      ),
      body: RefreshIndicator(
        onRefresh: () async {
          ref.invalidate(p2pTransferHistoryProvider(accountSequence));
        },
        child: recordsAsync.when(
          loading: () => const Center(child: CircularProgressIndicator()),
          error: (error, stack) => Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const Icon(Icons.error_outline, size: 48, color: _grayText),
                const SizedBox(height: 16),
                const Text(
                  '加载失败',
                  style: TextStyle(color: _grayText),
                ),
                const SizedBox(height: 8),
                TextButton(
                  onPressed: () => ref.invalidate(p2pTransferHistoryProvider(accountSequence)),
                  child: const Text('点击重试'),
                ),
              ],
            ),
          ),
          data: (allRecords) {
            // 按方向过滤
            final records = filterDirection == null
                ? allRecords
                : allRecords.where((r) {
                    final isSend = r.fromAccountSequence == accountSequence;
                    return filterDirection == 'send' ? isSend : !isSend;
                  }).toList();

            if (records.isEmpty) {
              return Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(
                      Icons.receipt_long,
                      size: 64,
                      color: _grayText.withOpacity(0.5),
                    ),
                    const SizedBox(height: 16),
                    Text(
                      _emptyText,
                      style: const TextStyle(
                        fontSize: 16,
                        color: _grayText,
                      ),
                    ),
                  ],
                ),
              );
            }

            return ListView.builder(
              padding: const EdgeInsets.all(16),
              itemCount: records.length,
              itemBuilder: (context, index) {
                return _buildRecordCard(context, records[index], accountSequence);
              },
            );
          },
        ),
      ),
    );
  }

  Widget _buildRecordCard(BuildContext context, P2pTransferModel record, String myAccountSequence) {
    // 判断是转出还是转入
    final isSend = record.fromAccountSequence == myAccountSequence;
    final statusColor = _getStatusColor(record.status);
    final statusText = _getStatusText(record.status);
    final dateFormat = DateFormat('yyyy-MM-dd HH:mm:ss');

    return Container(
      margin: const EdgeInsets.only(bottom: 12),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 标题行
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Row(
                children: [
                  Container(
                    width: 32,
                    height: 32,
                    decoration: BoxDecoration(
                      color: (isSend ? _orange : _green).withOpacity(0.1),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: Icon(
                      isSend ? Icons.arrow_upward : Icons.arrow_downward,
                      size: 18,
                      color: isSend ? _orange : _green,
                    ),
                  ),
                  const SizedBox(width: 12),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        isSend ? '转出' : '转入',
                        style: const TextStyle(
                          fontSize: 15,
                          fontWeight: FontWeight.w600,
                          color: _darkText,
                        ),
                      ),
                      const SizedBox(height: 2),
                      Text(
                        dateFormat.format(record.createdAt),
                        style: const TextStyle(
                          fontSize: 12,
                          color: _grayText,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                decoration: BoxDecoration(
                  color: statusColor.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(4),
                ),
                child: Text(
                  statusText,
                  style: TextStyle(
                    fontSize: 12,
                    color: statusColor,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
            ],
          ),
          const SizedBox(height: 12),
          const Divider(height: 1),
          const SizedBox(height: 12),
          // 转出：显示流水明细（转账金额 + 手续费 + 合计扣除）
          // 转入：只显示转账金额
          if (isSend) ...[
            // 转账金额
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                const Text(
                  '转账金额',
                  style: TextStyle(fontSize: 13, color: _grayText),
                ),
                Text(
                  '-${formatAmount(record.amount)} 积分值',
                  style: const TextStyle(fontSize: 13, color: _darkText),
                ),
              ],
            ),
            // 手续费
            if (double.tryParse(record.fee) != null && double.parse(record.fee) > 0) ...[
              const SizedBox(height: 6),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  const Text(
                    '手续费',
                    style: TextStyle(fontSize: 13, color: _grayText),
                  ),
                  Text(
                    '-${formatAmount(record.fee)} 积分值',
                    style: const TextStyle(fontSize: 13, color: _darkText),
                  ),
                ],
              ),
              const SizedBox(height: 8),
              const Divider(height: 1),
              const SizedBox(height: 8),
              // 合计扣除
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  const Text(
                    '合计扣除',
                    style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: _darkText),
                  ),
                  Text(
                    '-${formatAmount(_addAmounts(record.amount, record.fee))} 积分值',
                    style: TextStyle(
                      fontSize: 15,
                      fontWeight: FontWeight.bold,
                      color: _orange,
                    ),
                  ),
                ],
              ),
            ] else ...[
              // 无手续费时，转账金额用醒目样式
              // (已在上面显示，无需重复)
            ],
          ] else ...[
            // 转入：只显示金额
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                const Text(
                  '转账金额',
                  style: TextStyle(fontSize: 13, color: _grayText),
                ),
                Text(
                  '+${formatAmount(record.amount)} 积分值',
                  style: TextStyle(
                    fontSize: 15,
                    fontWeight: FontWeight.bold,
                    color: _green,
                  ),
                ),
              ],
            ),
          ],
          const SizedBox(height: 8),
          // 对方账号
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                isSend ? '收款方' : '付款方',
                style: const TextStyle(fontSize: 12, color: _grayText),
              ),
              Text(
                _maskPhone(record.toPhone),
                style: const TextStyle(
                  fontSize: 12,
                  color: _grayText,
                ),
              ),
            ],
          ),
          // 备注
          if (record.memo != null && record.memo!.isNotEmpty) ...[
            const SizedBox(height: 8),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                const Text(
                  '备注',
                  style: TextStyle(fontSize: 12, color: _grayText),
                ),
                Flexible(
                  child: Text(
                    record.memo!,
                    style: const TextStyle(
                      fontSize: 12,
                      color: _darkText,
                    ),
                    textAlign: TextAlign.right,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
              ],
            ),
          ],
          const SizedBox(height: 8),
          // 单号
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              const Text(
                '转账单号',
                style: TextStyle(fontSize: 12, color: _grayText),
              ),
              Text(
                record.transferNo,
                style: const TextStyle(
                  fontSize: 12,
                  color: _grayText,
                  fontFamily: 'monospace',
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  String _addAmounts(String a, String b) {
    final va = double.tryParse(a) ?? 0;
    final vb = double.tryParse(b) ?? 0;
    return (va + vb).toStringAsFixed(8);
  }

  String _maskPhone(String phone) {
    if (phone.length != 11) return phone;
    return '${phone.substring(0, 3)}****${phone.substring(7)}';
  }

  Color _getStatusColor(String status) {
    switch (status.toUpperCase()) {
      case 'COMPLETED':
      case 'SUCCESS':
        return _green;
      case 'PENDING':
        return _orange;
      case 'FAILED':
        return _red;
      default:
        return _grayText;
    }
  }

  String _getStatusText(String status) {
    switch (status.toUpperCase()) {
      case 'COMPLETED':
      case 'SUCCESS':
        return '已完成';
      case 'PENDING':
        return '处理中';
      case 'FAILED':
        return '失败';
      default:
        return status;
    }
  }
}
