import 'dart:core';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import '../../base/base_screen.dart';
import '../../base/basic_state.dart';
import '../../resources/base_color.dart';
import '../../widgets/custom_navigation_bar.dart';
import '../../widgets/image_loader.dart';
import '../voucher/models/product_model.dart';
import 'model/payment_bank_account_info_model.dart';
import 'model/payment_method_model.dart';
import 'model/preview_order_payment_model.dart';
import 'transaction_detail_viewmodel.dart';

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

  @override
  State<TransactionDetailScreen> createState() => _TransactionDetailScreenState();
}

class _TransactionDetailScreenState extends BaseState<TransactionDetailScreen> with BasicState {
  late final TransactionDetailViewModel _viewModel;
  final currencyFormatter = NumberFormat.currency(locale: 'vi_VN', symbol: 'đ', decimalDigits: 0);
  ProductModel? _product;
  int _quantity = 1;
  String? _targetPhoneNumber;
  bool _isPaymentMethodsExpanded = true;
  bool shouldDisablePaymentMethods = false;

  @override
  void initState() {
    super.initState();
    final args = Get.arguments;
    if (args is Map) {
      _product = args['product'];
      _quantity = args['quantity'] ?? 1;
      _targetPhoneNumber = args['targetPhoneNumber'];
    }
    if (_product == null) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        Get.back();
      });
      return;
    }
    _viewModel = Get.put(
      TransactionDetailViewModel(product: _product!, quantity: _quantity, targetPhoneNumber: _targetPhoneNumber),
    );
    _viewModel.refreshData();

    _viewModel.onShowAlertError = (message) {
      if (message.isNotEmpty) {
        showAlertError(content: message);
      }
    };
  }

  @override
  Widget createBody() {
    return Scaffold(
      backgroundColor: Colors.grey.shade50,
      appBar: CustomNavigationBar(title: "Thông tin thanh toán"),
      body: Obx(() {
        if (_viewModel.isLoading.value) {
          return const Center(child: CircularProgressIndicator());
        }
        final previewData = _viewModel.previewData.value;
        if (previewData == null) {
          return const Center(child: Text('Không có dữ liệu'));
        }
        final totalPrice = previewData.totalPrice ?? 0;
        final pointValue = previewData.pointData?.point ?? 0;
        shouldDisablePaymentMethods = _viewModel.usePoints.value && (_viewModel.finalTotal <= 0);
        return Column(
          children: [
            Expanded(
              child: SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    _buildProductInfoSection(previewData),
                    if (previewData.pointData != null) _buildPointToggleSection(),
                    _buildTotalSection(totalPrice, _viewModel.usePoints.value ? pointValue : 0, _viewModel.finalTotal),
                    _buildSavedCardsSection(),
                    _buildPaymentMethodsSection(),
                  ],
                ),
              ),
            ),
            _buildBottomBar(),
          ],
        );
      }),
    );
  }

  Widget _buildSectionHeader(String title) {
    return Container(
      color: Colors.grey.shade50,
      width: double.infinity,
      child: Padding(
        padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
        child: Text(title, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: Colors.black87)),
      ),
    );
  }

  Widget _buildProductInfoSection(PreviewOrderPaymentModel data) {
    final productInfo = data.productInfo ?? [];

    return Container(
      color: Colors.white,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildSectionHeader('Chi tiết giao dịch'),
          Column(
            children:
                productInfo.map((item) {
                  return Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        Expanded(
                          flex: 2,
                          child: Text(item.name ?? '', style: TextStyle(fontSize: 16, color: Colors.grey.shade700)),
                        ),
                        Expanded(
                          flex: 3,
                          child: Text(
                            item.value ?? '',
                            style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
                            textAlign: TextAlign.right,
                            softWrap: true,
                          ),
                        ),
                      ],
                    ),
                  );
                }).toList(),
          ),
        ],
      ),
    );
  }

  Widget _buildPointToggleSection() {
    final pointData = _viewModel.previewData.value?.pointData;
    if (pointData == null) {
      return const SizedBox.shrink();
    }
    return Container(
      color: Colors.white,
      margin: const EdgeInsets.only(top: 8),
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Row(
            children: [
              Center(child: Image.asset('assets/images/ic_point.png', width: 30, height: 30)),
              const SizedBox(width: 12),
              Text(pointData!.textDisplay ?? '', style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w500)),
            ],
          ),
          if (pointData!.isEnableUsePoint)
            Switch(
              activeColor: Colors.white,
              activeTrackColor: Colors.green,
              inactiveThumbColor: Colors.white,
              inactiveTrackColor: Colors.grey.shade400,
              value: _viewModel.usePoints.value,
              onChanged: (value) {
                setState(() {
                  _viewModel.usePoints.value = value;
                  final total = _viewModel.previewData.value?.totalPrice ?? 0;
                  final point = pointData!.point ?? 0;
                  shouldDisablePaymentMethods = value && (total - point <= 0);
                  if (!value && _viewModel.selectedPaymentMethodIndex < 0) {
                    if (_viewModel.paymentBankAccounts.value.isNotEmpty) {
                      _viewModel.selectedPaymentMethodIndex = _viewModel.definedCodeIndexBankAccount;
                    } else if (_viewModel.paymentMethods.value.isNotEmpty) {
                      _viewModel.selectedPaymentMethodIndex = 0;
                    }
                  }
                });
              },
            ),
        ],
      ),
    );
  }

  Widget _buildTotalSection(int totalPrice, int pointsUsed, int finalTotal) {
    return Container(
      color: Colors.white,
      margin: const EdgeInsets.only(top: 8),
      padding: const EdgeInsets.symmetric(vertical: 8),
      child: Column(
        children: [
          _buildTotalRow('Tổng số tiền', totalPrice, false),
          _buildTotalRow('Sử dụng điểm', -pointsUsed, false),
          _buildTotalRow('Tổng tạm tính', finalTotal, false),
        ],
      ),
    );
  }

  Widget _buildTotalRow(String label, int amount, bool isHighlighted) {
    final formattedAmount = currencyFormatter.format(amount);
    final displayAmount = amount < 0 ? formattedAmount : formattedAmount;

    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(label, style: TextStyle(fontSize: 16, color: isHighlighted ? Colors.black87 : Colors.grey.shade700)),
          Text(
            displayAmount,
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w500,
              color: isHighlighted && amount == 0 ? Colors.red : Colors.black87,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildSavedCardsSection() {
    return Obx(() {
      final bankAccounts = _viewModel.paymentBankAccounts;
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildSectionHeader('Tài khoản/Thẻ đã lưu'),
          IgnorePointer(
            ignoring: shouldDisablePaymentMethods,
            child: Opacity(
              opacity: shouldDisablePaymentMethods ? 0.6 : 1.0,
              child: Container(
                color: Colors.white,
                child:
                    bankAccounts.isEmpty
                        ? _buildNoSavedCardsItem()
                        : Row(
                          children: List.generate(
                            bankAccounts.length,
                            (index) => _buildSavedCardItem(bankAccounts[index], index),
                          ),
                        ),
              ),
            ),
          ),
        ],
      );
    });
  }

  Widget _buildNoSavedCardsItem() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
      child: Row(
        children: [
          Container(
            width: 40,
            height: 40,
            decoration: BoxDecoration(color: Colors.grey.shade200, borderRadius: BorderRadius.circular(4)),
            child: const Center(child: Icon(Icons.credit_card, color: Colors.grey)),
          ),
          const SizedBox(width: 12),
          const Text('Không có thẻ đã lưu', style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500)),
        ],
      ),
    );
  }

  Widget _buildSavedCardItem(PaymentBankAccountInfoModel account, int index) {
    final isSelected = _viewModel.selectedPaymentMethodIndex == _viewModel.definedCodeIndexBankAccount + index;
    return InkWell(
      onTap: () {
        setState(() {
          _viewModel.selectedPaymentMethodIndex =
              _viewModel.definedCodeIndexBankAccount + index; // tránh đụng index method
        });
      },
      child: IntrinsicWidth(
        child: Container(
          margin: const EdgeInsets.only(left: 16, right: 0, top: 8, bottom: 8),
          padding: const EdgeInsets.all(12),
          decoration: BoxDecoration(
            color: Colors.white,
            border: Border.all(color: isSelected ? Colors.red : Colors.grey.shade300, width: 1.5),
            borderRadius: BorderRadius.circular(8),
          ),
          child: Row(
            children: [
              if (account.bankLogo != null)
                ClipRRect(
                  borderRadius: BorderRadius.circular(4),
                  child: loadNetworkImage(
                    url: account.bankLogo,
                    width: 32,
                    height: 32,
                    placeholderAsset: 'assets/images/ic_logo.png',
                  ),
                ),
              const SizedBox(width: 12),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(account.bankShortName ?? '', style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w500)),
                  if (account.cardNumber != null)
                    Text(
                      '**** ${account.cardNumber!.substring(account.cardNumber!.length - 4)}',
                      style: TextStyle(color: Colors.grey.shade600),
                    ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildPaymentMethodsSection() {
    return Obx(() {
      final methods = _viewModel.paymentMethods;
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.fromLTRB(8, 8, 8, 0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: const Text(
                    'Phương thức thanh toán khác',
                    style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: Colors.black87),
                  ),
                ),
                IconButton(
                  icon: Icon(
                    _isPaymentMethodsExpanded ? Icons.keyboard_arrow_up : Icons.keyboard_arrow_down,
                    color: Colors.grey,
                  ),
                  onPressed: () {
                    setState(() {
                      _isPaymentMethodsExpanded = !_isPaymentMethodsExpanded;
                    });
                  },
                ),
              ],
            ),
          ),
          if (_isPaymentMethodsExpanded)
            IgnorePointer(
              ignoring: shouldDisablePaymentMethods,
              child: Opacity(
                opacity: shouldDisablePaymentMethods ? 0.6 : 1.0,
                child: Container(
                  color: Colors.white,
                  child: Column(
                    children: List.generate(methods.length, (index) => _buildPaymentMethodItem(methods[index], index)),
                  ),
                ),
              ),
            ),
        ],
      );
    });
  }

  Widget _buildPaymentMethodItem(PaymentMethodModel method, int index) {
    final isSelected = _viewModel.selectedPaymentMethodIndex == index;
    final canSaveToken = method.saveToken == true;
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        RadioListTile<int>(
          activeColor: BaseColor.primary400,
          value: index,
          groupValue: _viewModel.selectedPaymentMethodIndex,
          onChanged: (val) {
            setState(() {
              _viewModel.selectedPaymentMethodIndex = val!;
            });
          },
          contentPadding: const EdgeInsets.symmetric(horizontal: 8),
          title: Row(
            children: [
              if (method.logo != null)
                Padding(
                  padding: const EdgeInsets.only(right: 8),
                  child: Image.network(
                    method.logo!,
                    width: 24,
                    height: 24,
                    errorBuilder: (_, __, ___) => const Icon(Icons.payment),
                  ),
                ),
              Text(method.name ?? '', style: const TextStyle(fontSize: 16)),
            ],
          ),
        ),
        if (isSelected && canSaveToken)
          Padding(
            padding: const EdgeInsets.only(left: 48, right: 16),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                const Text("Lưu lại thanh toán sau", style: TextStyle(fontSize: 14, color: Colors.black87)),
                Switch(
                  activeColor: Colors.white,
                  activeTrackColor: Colors.green,
                  inactiveThumbColor: Colors.white,
                  inactiveTrackColor: Colors.grey.shade400,
                  value: method.needSaveTokenWhenOrder ?? true,
                  onChanged: (val) {
                    setState(() {
                      method.needSaveTokenWhenOrder = val;
                    });
                  },
                ),
              ],
            ),
          ),
        Container(height: 1, color: Colors.grey.shade200, margin: const EdgeInsets.symmetric(horizontal: 16)),
      ],
    );
  }

  Widget _buildBottomBar() {
    return SafeArea(
      top: false,
      minimum: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
      child: Container(
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: Colors.white,
          boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.05), blurRadius: 10, offset: const Offset(0, -5))],
        ),
        child: Column(
          children: [
            if ((_viewModel.previewData.value?.feeNote ?? "").isNotEmpty)
              Text(
                _viewModel.previewData.value?.feeNote ?? '',
                style: TextStyle(fontSize: 12, color: Colors.orange.shade700),
              ),
            const SizedBox(height: 12),
            Container(height: 1, color: Colors.grey.shade200),
            const SizedBox(height: 12),
            Row(
              children: [
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      const Text('Tổng thanh toán', style: TextStyle(fontSize: 14, color: Colors.grey)),
                      const SizedBox(height: 4),
                      Text(
                        currencyFormatter.format(_viewModel.finalTotal),
                        style: const TextStyle(fontSize: 22, fontWeight: FontWeight.bold),
                      ),
                    ],
                  ),
                ),
                ElevatedButton(
                  onPressed:
                      _viewModel.finalTotal > 0 && _viewModel.selectedPaymentMethodIndex < 0
                          ? null
                          : _viewModel.requestPaymentProduct,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: BaseColor.primary500,
                    foregroundColor: Colors.white,
                    padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 16),
                    shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
                    disabledBackgroundColor: Colors.red.withOpacity(0.6),
                    disabledForegroundColor: Colors.white.withOpacity(0.8),
                  ),
                  child: const Text('Tiếp tục', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
                ),
              ],
            ),
            // const SizedBox(height: 44),
          ],
        ),
      ),
    );
  }
}
