import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/screen/transaction/history/transaction_history_emun.dart';
import 'package:mypoint_flutter_app/shared/router_gage.dart';
import 'package:mypoint_flutter_app/widgets/dashed_line.dart';
import '../../../base/base_screen.dart';
import '../../../base/basic_state.dart';
import '../../../resources/base_color.dart';
import '../../../widgets/back_button.dart';
import '../../../widgets/custom_navigation_bar.dart';
import '../../../widgets/custom_toast_message.dart';
import '../../../widgets/image_loader.dart';
import 'transaction_history_detail_viewmodel.dart';
import 'transaction_history_model.dart';

class TransactionHistoryDetailScreen extends BaseScreen {
  const TransactionHistoryDetailScreen({super.key});

  @override
  State<TransactionHistoryDetailScreen> createState() => _TransactionHistoryDetailScreenState();
}

class _TransactionHistoryDetailScreenState extends BaseState<TransactionHistoryDetailScreen> with BasicState {
  late final TransactionHistoryDetailViewModel _viewModel;
  late var canBack = true;

  @override
  void initState() {
    super.initState();
    final args = Get.arguments;
    canBack = args['canBack'] as bool? ?? true;
    final orderId = args['orderId'] as String? ?? '';
    _viewModel = Get.put(TransactionHistoryDetailViewModel(orderID: orderId));
    _viewModel.onShowAlertError = (message) {
      if (message.isNotEmpty) {
        showAlertError(content: message);
      }
    };
  }

  @override
  Widget createBody() {
    return Scaffold(
      backgroundColor: Colors.grey.shade100,
      appBar: CustomNavigationBar(
        title: 'Chi tiết giao dịch',
        leftButtons: canBack ? [CustomBackButton()] : [],
        rightButtons: [
          IconButton(
            icon: const Icon(Icons.headset_rounded, size: 24),
            onPressed: () {
              Get.toNamed(supportScreen);
            },
          ),
        ],
      ),
      body: Obx(() {
        final isLoading = _viewModel.isLoading.value;
        final data = _viewModel.transactionData.value;
        if (isLoading) {
          return const Center(child: CircularProgressIndicator());
        }
        if (data == null) {
          return const Center(child: Text('Không tìm thấy dữ liệu giao dịch'));
        }
        return Column(
          children: [
            Expanded(
              child: IntrinsicHeight(
                child: SingleChildScrollView(
                  child: Container(
                    padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
                    margin: const EdgeInsets.all(20),
                    decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(12)),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        _buildMainInfoSection(data),
                        DashedLine(),
                        const SizedBox(height: 12),
                        _buildDetailInfoSection(data),
                        const SizedBox(height: 12),
                        DashedLine(),
                        const Divider(height: 12),
                        _buildProductInfoSection(data),
                      ],
                    ),
                  ),
                ),
              ),
            ),
            _buildBottomButton(data),
          ],
        );
      }),
    );
  }

  Widget _buildMainInfoSection(TransactionHistoryModel data) {
    return Center(
      child: Container(
        padding: const EdgeInsets.all(0),
        decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(12)),
        child: Column(
          children: [
            SizedBox(
              width: 60,
              height: 60,
              child: loadNetworkImage(
                url: data.logo ?? "",
                fit: BoxFit.cover,
                placeholderAsset: 'assets/images/ic_logo.png',
              ),
            ),
            const SizedBox(height: 8),
            Text(data.name ?? "Thanh toán mua ưu đãi", style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold), textAlign: TextAlign.center),
            const SizedBox(height: 4),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                if ((data.payCash ?? '').isNotEmpty)
                  Text(
                    '${data.payCash}',
                    style: const TextStyle(fontSize: 20, color: Colors.red, fontWeight: FontWeight.bold),
                  ),
                if ((data.payCash ?? '').isNotEmpty && (data.payPoint ?? '').isNotEmpty) const SizedBox(width: 24),
                if ((data.payPoint ?? '').isNotEmpty)
                  Row(
                    children: [
                      Image.asset('assets/images/ic_point.png', width: 24, height: 24),
                      const SizedBox(width: 4),
                      Text(
                        data.payPoint ?? '0',
                        style: const TextStyle(fontSize: 20, color: Colors.red, fontWeight: FontWeight.bold),
                      ),
                    ],
                  ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildDetailInfoSection(TransactionHistoryModel data) {
    return Container(
      margin: const EdgeInsets.only(top: 8),
      color: Colors.white,
      child: Column(
        children: [
          _buildDetailRow(title: "Trạng thái", value: data.status ?? '', valueColor: _getStatusColor(data.statusT)),
          _buildDetailRow(title: "Thời gian", value: data.createdAt ?? ''),
          const SizedBox(height: 12),
          DashedLine(),
          const SizedBox(height: 12),
          _buildDetailRow(
            title: "Mã giao dịch",
            value: data.transactionId ?? '',
            trailing: SizedBox(
              width: 32,
              height: 32,
              child: Center(
                child: IconButton(
                  icon: const Icon(Icons.copy, size: 16, color: BaseColor.primary500),
                  onPressed: () {
                    Clipboard.setData(ClipboardData(text: data.transactionId ?? ''));
                    showToastMessage('Đã sao chép mã giao dịch');
                  },
                ),
              ),
            ),
          ),
          _buildDetailRow(title: "Nguồn tiền", value: data.sourceCash ?? ''),
          _buildDetailRow(title: "Phí thanh toán", value: data.feesPrice ?? ''),
        ],
      ),
    );
  }

  Widget _buildProductInfoSection(TransactionHistoryModel data) {
    final productInfo = data.productInfo;
    if (productInfo == null || productInfo.isEmpty) {
      return const SizedBox.shrink();
    }
    return Container(
      margin: const EdgeInsets.only(top: 8),
      color: Colors.white,
      child: Column(
        children:
            productInfo.map((info) {
              return Column(
                children: [
                  _buildDetailRow(title: info.name ?? '', value: info.value ?? ''),
                  // if (productInfo.last != info) _buildDivider(),
                ],
              );
            }).toList(),
      ),
    );
  }

  Widget _buildDetailRow({required String title, required String value, Widget? trailing, Color? valueColor}) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 6),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          SizedBox(
            width: 150,
            child: Text(
              title,
              style: const TextStyle(fontSize: 15, color: Colors.black87, fontWeight: FontWeight.w400),
            ),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Expanded(
                  child: Text(
                    value,
                    textAlign: TextAlign.right,
                    style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500, color: valueColor ?? Colors.black),
                  ),
                ),
                if (trailing != null) ...[
                  // const SizedBox(height: 4),
                  trailing,
                ],
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildBottomButton(TransactionHistoryModel transaction) {
    return SafeArea(
      top: false,
      minimum: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
      child: Container(
        width: double.infinity,
        padding: const EdgeInsets.all(12),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            if (transaction.titleRedButton != null)
              ElevatedButton(
                onPressed: () {
                  final finish = transaction.directionScreenRedButton?.begin();
                  if (finish != true) {
                    Get.until((route) => Get.currentRoute == mainScreen);
                  }
                },
                style: ElevatedButton.styleFrom(
                  backgroundColor: BaseColor.primary600,
                  foregroundColor: Colors.white,
                  minimumSize: const Size(double.infinity, 50),
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
                ),
                child: Text(
                  transaction.titleRedButton,
                  style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                ),
              ),
            const SizedBox(height: 12),
            if (transaction.titleClearButton != null)
              TextButton(
                onPressed: () {
                  Get.until((route) => Get.currentRoute == mainScreen);
                },
                style: TextButton.styleFrom(
                  minimumSize: const Size(double.infinity, 50),
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
                ),
                child: Text(
                  transaction.titleClearButton ?? '',
                  style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500, color: Colors.grey.shade700),
                ),
              ),
          ],
        ),
      ),
    );
  }

  Color _getStatusColor(TransactionStatusOrder status) {
    switch (status) {
      case TransactionStatusOrder.success:
        return Colors.green;
      case TransactionStatusOrder.failed:
        return Colors.red;
      case TransactionStatusOrder.processing:
      default:
        return Colors.orange;
    }
  }
}
