import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/extensions/num_extension.dart';
import 'package:mypoint_flutter_app/screen/mobile_card/product_mobile_card_viewmodel.dart';
import 'package:mypoint_flutter_app/screen/mobile_card/usable_mobile_card_popup.dart';
import 'package:mypoint_flutter_app/widgets/image_loader.dart';
import '../../base/base_screen.dart';
import '../../base/basic_state.dart';
import '../../resources/base_color.dart';
import '../../widgets/alert/custom_alert_dialog.dart';
import '../../widgets/alert/data_alert_model.dart';
import '../../widgets/custom_navigation_bar.dart';

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

  @override
  State<ProductMobileCardScreen> createState() => _ProductMobileCardScreenState();
}

class _ProductMobileCardScreenState extends BaseState<ProductMobileCardScreen> with BasicState {
  late final ProductMobileCardViewModel _viewModel;

  @override
  void initState() {
    super.initState();
    _viewModel = ProductMobileCardViewModel();
    _viewModel.getProductMobileCard();
    _viewModel.onShowAlertError = (message) {
      if (message.isNotEmpty) {
        showAlertError(content: message);
      }
    };
    _viewModel.onRedeemProductMobileSuccess = (data) {
      if (data != null) {
        showVoucherPopup(context, data);
      } else {
        showAlertError(content: "Đổi mã thẻ nạp thất bại, vui lòng thử lại sau!");
      }
    };
  }

  @override
  Widget createBody() {
    return Scaffold(
      appBar: CustomNavigationBar(title: "Đổi mã thẻ nạp"),
      body: Obx(() {
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Padding(
              padding: EdgeInsets.symmetric(horizontal: 16, vertical: 12),
              child: Text("Chọn nhà mạng", style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16)),
            ),
            _buildSectionNetwork(),
            const SizedBox(height: 24),
            const Padding(
              padding: EdgeInsets.symmetric(horizontal: 16),
              child: Text("Mệnh giá thẻ", style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16)),
            ),
            const SizedBox(height: 12),
            _buildProductItem(),
            SafeArea(
              child: Padding(
                padding: const EdgeInsets.all(16),
                child: ElevatedButton(
                  onPressed: _viewModel.selectedProduct == null ? null : _redeemProductMobileCard,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: _viewModel.selectedProduct == null ? Colors.grey : BaseColor.primary500,
                    shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                    minimumSize: const Size.fromHeight(48),
                  ),
                  child: const Text(
                    "Xác nhận",
                    style: TextStyle(fontSize: 16, color: Colors.white, fontWeight: FontWeight.bold),
                  ),
                ),
              ),
            ),
          ],
        );
      }),
    );
  }

  Widget _buildSectionNetwork() {
    final widthCardItem = MediaQuery.of(context).size.width / 2.5;
    return SizedBox(
      height: widthCardItem * 9 / 16,
      child: ListView.separated(
        padding: const EdgeInsets.symmetric(horizontal: 16),
        scrollDirection: Axis.horizontal,
        itemCount: _viewModel.mobileCardSections.value.length,
        separatorBuilder: (_, __) => const SizedBox(width: 12),
        itemBuilder: (_, index) {
          final mobileCard = _viewModel.mobileCardSections.value[index];
          final isSelected = mobileCard.brandCode == _viewModel.selectedBrandCode.value;
          return GestureDetector(
            onTap: () {
              setState(() {
                if (_viewModel.selectedBrandCode.value == mobileCard.brandCode) return;
                _viewModel.selectedBrandCode.value = mobileCard.brandCode ?? "";
                _viewModel.selectedProduct = null;
              });
            },
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 20),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(12),
                border: Border.all(color: isSelected ? Colors.orange : Colors.grey.shade300, width: 2),
                color: Colors.white,
              ),
              alignment: Alignment.center,
              child: loadNetworkImage(
                url: mobileCard.brandLogo,
                width: widthCardItem,
                placeholderAsset: "assets/images/bg_default_169.png",
              ),
            ),
          );
        },
      ),
    );
  }

  Widget _buildProductItem() {
    const double kItemHeight = 80;
    final widthItem = (MediaQuery.of(context).size.width - 12*3)/2;
    return Expanded(
      child: GridView.count(
        crossAxisCount: 2,
        padding: const EdgeInsets.symmetric(horizontal: 16),
        crossAxisSpacing: 12,
        mainAxisSpacing: 12,
        childAspectRatio: widthItem/kItemHeight,
        children:
            _viewModel.products.map((product) {
              final isSelected = _viewModel.selectedProduct?.id == product.id;
              final amount =
                  int.tryParse(
                    (product.prices?.isNotEmpty == true) ? product.prices?.first.originalPrice ?? "0" : "0",
                  ) ??
                  0;
              final price =
                  int.tryParse((product.prices?.isNotEmpty == true) ? product.prices?.first.payPoint ?? "0" : "0") ?? 0;
              return GestureDetector(
                onTap: () {
                  setState(() {
                    _viewModel.selectedProduct = product;
                  });
                },
                child: Container(
                  decoration: BoxDecoration(
                    border: Border.all(color: isSelected ? Colors.orange : Colors.grey.shade300),
                    borderRadius: BorderRadius.circular(12),
                    color: isSelected ? Colors.orange.withOpacity(0.1) : Colors.white,
                  ),
                  padding: const EdgeInsets.all(10),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        amount.money(CurrencyUnit.vnd),
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 16,
                          color: isSelected ? Colors.orange : Colors.black87,
                        ),
                      ),
                      const SizedBox(height: 4),
                      Row(
                        children: [
                          Text(
                            "Giá: ${price.money(CurrencyUnit.none)}",
                            style: TextStyle(fontSize: 14, color: isSelected ? Colors.orange : Colors.black54),
                          ),
                          Image.asset("assets/images/ic_point.png", width: 16, height: 16),
                        ],
                      ),
                    ],
                  ),
                ),
              );
            }).toList(),
      ),
    );
  }

  _redeemProductMobileCard() {
    if (_viewModel.selectedProduct == null) return;
    if (!_viewModel.isValidBalance) {
      showAlertError(content: "Bạn chưa đủ điểm để đổi ưu đãi này, vui lòng tích lũy thêm điểm nhé!");
      return;
    }
    _showAlertConfirmRedeemProduct();
  }

  _showAlertConfirmRedeemProduct() {
    final dataAlert = DataAlertModel(
      title: "Xác nhận",
      description: "Bạn có muốn sử dụng ${_viewModel.payPoint.money(CurrencyUnit.point)} MyPoint để đổi lấy mã thẻ điện thoại này không?",
      localHeaderImage: "assets/images/ic_pipi_02.png",
      buttons: [
        AlertButton(
          text: "Đồng ý",
          onPressed: () {
            Get.back();
            _viewModel.redeemProductMobileCard();
          },
          bgColor: BaseColor.primary500,
          textColor: Colors.white,
        ),
        AlertButton(text: "Huỷ", onPressed: () => Get.back(), bgColor: Colors.white, textColor: BaseColor.second500),
      ],
    );
    showAlert(data: dataAlert, direction: ButtonsDirection.row);
  }
}
