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 '../../../domain/repositories/trading_repository.dart';
import '../../providers/trading_providers.dart';

/// 划转记录数据模型
class TransferRecord {
  final String transferNo;
  final String direction; // IN: 划入交易账户, OUT: 划出到挖矿账户
  final String amount;
  final String status; // PENDING, COMPLETED, FAILED
  final DateTime createdAt;
  final DateTime? completedAt;
  final String? errorMessage;

  TransferRecord({
    required this.transferNo,
    required this.direction,
    required this.amount,
    required this.status,
    required this.createdAt,
    this.completedAt,
    this.errorMessage,
  });

  factory TransferRecord.fromJson(Map<String, dynamic> json) {
    return TransferRecord(
      transferNo: json['transferNo'] ?? '',
      direction: json['direction'] ?? '',
      amount: json['amount']?.toString() ?? '0',
      status: json['status'] ?? '',
      createdAt: DateTime.tryParse(json['createdAt'] ?? '') ?? DateTime.now(),
      completedAt: json['completedAt'] != null
          ? DateTime.tryParse(json['completedAt'])
          : null,
      errorMessage: json['errorMessage'],
    );
  }
}

/// 划转记录页面 Provider
final transferRecordsProvider = FutureProvider<List<TransferRecord>>((ref) async {
  final repository = ref.watch(tradingRepositoryProvider);
  final result = await repository.getTransferHistory();

  return result.fold(
    (failure) => throw Exception(failure.message),
    (records) => records.map((json) => TransferRecord.fromJson(json as Map<String, dynamic>)).toList(),
  );
});

class TransferRecordsPage extends ConsumerWidget {
  const TransferRecordsPage({super.key});

  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);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final recordsAsync = ref.watch(transferRecordsProvider);

    return Scaffold(
      backgroundColor: _bgGray,
      appBar: AppBar(
        title: const Text(
          '划转记录',
          style: 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(transferRecordsProvider);
        },
        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),
                Text(
                  '加载失败',
                  style: TextStyle(color: _grayText),
                ),
                const SizedBox(height: 8),
                TextButton(
                  onPressed: () => ref.invalidate(transferRecordsProvider),
                  child: const Text('点击重试'),
                ),
              ],
            ),
          ),
          data: (records) {
            if (records.isEmpty) {
              return Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(
                      Icons.swap_horiz,
                      size: 64,
                      color: _grayText.withValues(alpha: 0.5),
                    ),
                    const SizedBox(height: 16),
                    const Text(
                      '暂无划转记录',
                      style: TextStyle(
                        fontSize: 16,
                        color: _grayText,
                      ),
                    ),
                  ],
                ),
              );
            }

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

  Widget _buildRecordCard(TransferRecord record) {
    final isIn = record.direction == 'IN';
    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: (isIn ? _green : _orange).withValues(alpha: 0.1),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: Icon(
                      isIn ? Icons.arrow_downward : Icons.arrow_upward,
                      size: 18,
                      color: isIn ? _green : _orange,
                    ),
                  ),
                  const SizedBox(width: 12),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        isIn ? '划入交易账户' : '划出到挖矿账户',
                        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.withValues(alpha: 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),
          // 数量
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              const Text(
                '划转数量',
                style: TextStyle(fontSize: 13, color: _grayText),
              ),
              Text(
                '${isIn ? '+' : '-'}${formatAmount(record.amount)} 积分股',
                style: TextStyle(
                  fontSize: 15,
                  fontWeight: FontWeight.bold,
                  color: isIn ? _green : _orange,
                ),
              ),
            ],
          ),
          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',
                ),
              ),
            ],
          ),
          // 错误信息
          if (record.status == 'FAILED' && record.errorMessage != null) ...[
            const SizedBox(height: 8),
            Container(
              padding: const EdgeInsets.all(8),
              decoration: BoxDecoration(
                color: _red.withValues(alpha: 0.05),
                borderRadius: BorderRadius.circular(4),
              ),
              child: Row(
                children: [
                  const Icon(Icons.info_outline, size: 14, color: _red),
                  const SizedBox(width: 4),
                  Expanded(
                    child: Text(
                      record.errorMessage!,
                      style: const TextStyle(
                        fontSize: 12,
                        color: _red,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ],
      ),
    );
  }

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

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