import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:get/get_state_manager/src/rx_flutter/rx_obx_widget.dart';
import 'package:mypoint_flutter_app/extensions/num_extension.dart';
import 'package:mypoint_flutter_app/widgets/image_loader.dart';
import '../../resources/base_color.dart';
import '../../shared/router_gage.dart';
import '../../widgets/custom_navigation_bar.dart';
import '../transaction/model/payment_method_model.dart';
import '../webview/payment_web_view_screen.dart';
import 'models/customer_contract_object_model.dart';
import 'electric_payment_bill_viewmodel.dart';

class ElectricPaymentBillScreen extends StatefulWidget {
  final CustomerContractModel bill;
  const ElectricPaymentBillScreen({super.key, required this.bill});

  @override
  State<ElectricPaymentBillScreen> createState() => _ElectricPaymentBillScreenState();
}

class _ElectricPaymentBillScreenState extends State<ElectricPaymentBillScreen> {
  final _viewModel = ElectricPaymentBillViewModel();

  @override
  void initState() {
    super.initState();
    _viewModel.customerEvnPaymentGatewayResponse = (data) {
      Get.toNamed(
          paymentWebViewScreen,
          arguments: PaymentWebViewInput(
            url: data?.vitapayData ?? "",
            isContract: false,
            orderId: data?.requestId ?? "",
            showAlertBack: false,
            callback: (result) {
              if (result == PaymentProcess.success) {
                Get.offNamed(
                  transactionHistoryDetailScreen,
                  arguments: {"orderId": data?.requestId ?? "", "canBack": true},
                );
              }
            },
          )
      );
    };
    _viewModel.getPaymentMethods();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CustomNavigationBar(title: 'Chi tiết hóa đơn điện'),
      body: LayoutBuilder(
        builder: (context, constraints) {
          return SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Padding(
                  padding: const EdgeInsets.all(16),
                  child: Row(
                    children: [
                      Image.asset('assets/images/ic_evn_logo.png', height: 48, fit: BoxFit.cover),
                      const SizedBox(width: 12),
                      Text(
                        'Điện lực ${widget.bill.location ?? ''}',
                        style: TextStyle(fontSize: 18, color: Colors.blueAccent, fontWeight: FontWeight.w700),
                      ),
                    ],
                  ),
                ),
                Divider(thickness: 1, color: Colors.grey[200]),
                const SizedBox(height: 4),
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 16),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      _buildInfoRow('Mã khách hàng:', widget.bill.maKH),
                      _buildInfoRow('Tên khách hàng:', widget.bill.nameKH),
                      _buildInfoRow('Mã hóa đơn:', widget.bill.idHoaHon),
                      _buildInfoRow('Kỳ hóa đơn:', widget.bill.ky),
                      _buildInfoRow(
                        'Tổng giá trị hóa đơn:',
                        (widget.bill.amount ?? 0).money(CurrencyUnit.VND),
                        valueColor: Colors.orange,
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: 16),
                Divider(thickness: 1, color: Colors.grey[200]),
                const SizedBox(height: 16),
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 16),
                  child: Text(
                    'Phương thức thanh toán',
                    style: TextStyle(fontSize: 18, color: Colors.black87, fontWeight: FontWeight.w600),
                  ),
                ),
                const SizedBox(height: 12),
                _buildPaymentMethods(),
              ],
            ),
          );
        },
      ),
      bottomNavigationBar: _buildBottomButton(),
    );
  }

  Widget _buildBottomButton() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
      decoration: const BoxDecoration(
        color: Colors.white,
        boxShadow: [BoxShadow(color: Colors.black54, blurRadius: 8, offset: Offset(0, 4))],
      ),
      child: SafeArea(
        top: false,
        child: ElevatedButton(
          onPressed: () {
            _viewModel.customerEvnPaymentGatewayRequest(widget.bill);
          },
          style: ElevatedButton.styleFrom(
            backgroundColor: BaseColor.primary500,
            minimumSize: const Size.fromHeight(52),
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
          ),
          child: Text('Thanh toán', style: TextStyle(fontSize: 16, color: Colors.white, fontWeight: FontWeight.w700)),
        ),
      ),
    );
  }

  Widget _buildInfoRow(String label, String? value, {Color? valueColor}) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 6),
      child: Row(
        children: [
          SizedBox(
            width: 180,
            child: Text(
              label,
              style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w500, color: Colors.black54),
            ),
          ),
          Text(
            textAlign: TextAlign.start,
            value ?? '',
            style: TextStyle(
              fontSize: 17,
              color: valueColor ?? Colors.black87,
              fontWeight: valueColor != null ? FontWeight.bold : FontWeight.normal,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildPaymentMethods() {
    final methods = _viewModel.paymentMethods;
    return Obx(
      () => Container(
        margin: const EdgeInsets.symmetric(horizontal: 16),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(8),
          color: Colors.white,
          border: Border.all(color: Colors.grey.shade300, width: 1),
        ),
        child: Column(
          children: List.generate(methods.length, (index) => _buildPaymentMethodItem(methods[index], index)),
        ),
      ),
    );
  }

  Widget _buildPaymentMethodItem(PaymentMethodModel method, int index) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        RadioListTile<int>(
          activeColor: BaseColor.primary400,
          value: index,
          groupValue: _viewModel.selectedPaymentMethodIndex.value,
          onChanged: (val) {
            setState(() {
              _viewModel.selectedPaymentMethodIndex.value = val ?? 0;
            });
          },
          contentPadding: const EdgeInsets.symmetric(horizontal: 8),
          title: Row(
            children: [
              if (method.logo != null)
                Padding(
                  padding: const EdgeInsets.only(right: 8),
                  child: loadNetworkImage(
                    url: method.logo,
                    width: 24,
                    height: 24,
                    fit: BoxFit.cover,
                    placeholderAsset: 'assets/images/ic_logo.png',
                  ),
                ),
              Text(method.name ?? '', style: const TextStyle(fontSize: 16)),
            ],
          ),
        ),
        if (index < _viewModel.paymentMethods.length - 1)
          Container(height: 1, color: Colors.grey.shade200, margin: const EdgeInsets.symmetric(horizontal: 16)),
      ],
    );
  }
}
