import 'dart:async';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/core/utils/extensions/num_extension.dart';
import 'package:mypoint_flutter_app/core/utils/extensions/string_extension.dart';
import 'package:mypoint_flutter_app/features/data_network_service/product_network_data_model.dart';
import 'package:mypoint_flutter_app/shared/widgets/custom_empty_widget.dart';
import 'package:mypoint_flutter_app/shared/widgets/custom_navigation_bar.dart';
import 'package:mypoint_flutter_app/shared/widgets/image_loader.dart';
import '../../shared/widgets/base_view/base_screen.dart';
import '../../shared/widgets/base_view/basic_state.dart';
import '../../core/utils/debouncer.dart';
import '../../shared/preferences/data_preference.dart';
import '../../shared/preferences/point/point_manager.dart';
import '../../core/theme/base_color.dart';
import '../../shared/widgets/alert/custom_alert_dialog.dart';
import '../../shared/widgets/alert/data_alert_model.dart';
import '../contacts/contacts_picker.dart';
import '../topup/brand_select_sheet_widget.dart';
import 'data_network_service_viewmodel.dart';

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

  @override
  State<DataNetworkServiceScreen> createState() => _DataNetworkServiceScreenState();
}

class _DataNetworkServiceScreenState extends BaseState<DataNetworkServiceScreen> with BasicState {
  final DataNetworkServiceViewModel _viewModel = Get.put(DataNetworkServiceViewModel());
  late final TextEditingController _phoneController;
  final _deb = Debouncer(ms: 500);

  @override
  void initState() {
    super.initState();
    _phoneController = TextEditingController(text: _viewModel.phoneNumber.value);
    _viewModel.firstLoadNetworkData();

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

  @override
  Widget createBody() {
    return Scaffold(
      appBar: CustomNavigationBar(title: "Ưu đãi Data"),
      body: Obx(() {
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildHeaderPhone(),
            Container(height: 6, color: Colors.grey.shade200),
            const Divider(height: 8),
            if (_viewModel.topUpNetworkData.isEmpty)
              Expanded(child: EmptyWidget(isLoading: _viewModel.isLoading.value)),
            if (_viewModel.topUpNetworkData.isNotEmpty)
              Expanded(
                child: ListView.builder(
                  physics: const AlwaysScrollableScrollPhysics(),
                  itemCount: _viewModel.topUpNetworkData.length,
                  itemBuilder: (context, index) {
                    final data = _viewModel.topUpNetworkData.value[index];
                    return _buildSectionNetworkData(data);
                  },
                ),
              ),
            const Divider(height: 1),
            SafeArea(child: Padding(padding: const EdgeInsets.only(left: 16, right: 16, top: 8, bottom: 8), child: _buildButton())),
          ],
        );
      }),
    );
  }

  Widget _buildButton() {
    return Obx(() {
      final isValidInput = _viewModel.phoneNumber.value.isPhoneValid() && (_viewModel.selectedProduct.value != null);
      return ElevatedButton(
        onPressed: isValidInput ? _redeemProductMobileCard : null,
        style: ElevatedButton.styleFrom(
          backgroundColor: isValidInput ? BaseColor.primary500 : Colors.grey,
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
          minimumSize: const Size.fromHeight(48),
        ),
        child: const Text("Đổi ngay", style: TextStyle(fontSize: 16, color: Colors.white, fontWeight: FontWeight.bold)),
      );
    });
  }

  void _redeemProductMobileCard() {
    debugPrint("redeem ${UserPointManager().point} >= ${_viewModel.payPoint}");
    final isValidInput =
        (_viewModel.phoneNumber.value.trim().length >= 10) && (_viewModel.selectedProduct.value != null);
    if (!isValidInput) {
      showAlertError(content: "Vui lòng chọn gói cước và nhập số điện thoại.");
      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();
  }

  void _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 gói cước 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);
  }

  Widget _buildSectionNetworkData(TopUpNetworkDataModel data) {
    final packages = data.products ?? [];
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
          child: Text(
            textAlign: TextAlign.start,
            data.groupName,
            style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
          ),
        ),
        GridView.builder(
          padding: const EdgeInsets.symmetric(horizontal: 16),
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          itemCount: packages.length,
          gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2,
            childAspectRatio: 2.8,
            crossAxisSpacing: 8,
            mainAxisSpacing: 12,
          ),
          itemBuilder: (context, index) {
            final item = packages[index];
            final isSelected = _viewModel.selectedProduct.value?.id == item.id;
            return GestureDetector(
              onTap: () {
                setState(() {
                  _viewModel.selectedProduct.value = item;
                });
              },
              child: Container(
                decoration: BoxDecoration(
                  border: Border.all(color: isSelected ? Colors.orange : Colors.grey.shade300),
                  borderRadius: BorderRadius.circular(8),
                ),
                padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 0),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Text(
                          item.name ?? '',
                          style: const TextStyle(
                            color: BaseColor.primary500,
                            fontWeight: FontWeight.bold,
                            fontSize: 18,
                          ),
                        ),
                        const SizedBox(width: 2),
                        Text(
                          '/ ${item.dataDurationApply}',
                          style: const TextStyle(fontSize: 14, color: Colors.black87),
                        ),
                      ],
                    ),
                    const SizedBox(height: 3),
                    Row(
                      children: [
                        Image.asset("assets/images/ic_point.png", width: 18, height: 18, fit: BoxFit.cover),
                        const SizedBox(width: 2),
                        Text(
                          item.payPoint.money(CurrencyUnit.none),
                          style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 14, color: Colors.orange),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            );
          },
        ),
      ],
    );
  }

  Widget _buildHeaderPhone() {
    return Obx(() {
      return Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const SizedBox(height: 8),
            const Text("Số điện thoại", style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16)),
            const SizedBox(height: 8),
            Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: _phoneController,
                    decoration: InputDecoration(
                      filled: true,
                      fillColor: Colors.grey.shade100,
                      suffixIcon: InkWell(
                        onTap: () => pickContact(context),
                        child: const Icon(Icons.contacts, color: Colors.orange),
                      ),
                      border: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: BorderSide.none),
                    ),
                    keyboardType: TextInputType.phone,
                    onChanged: (value) {
                      _viewModel.phoneNumber.value = value;
                      _deb.run(() => _viewModel.checkMobileNetwork());
                    },
                  ),
                ),
                const SizedBox(width: 8),
                GestureDetector(
                  onTap:
                      _viewModel.topUpBrands.value.isEmpty
                          ? null
                          : () {
                            showModalBottomSheet(
                              context: context,
                              backgroundColor: Colors.transparent,
                              isScrollControlled: true,
                              builder:
                                  (_) => BrandSelectSheet(
                                    brands: _viewModel.topUpBrands.value,
                                    selectedBrand: _viewModel.selectedBrand.value,
                                    onSelected: (brand) {
                                      Navigator.pop(context);
                                      if (brand.id != _viewModel.selectedBrand.value?.id) return;
                                      _viewModel.selectedProduct.value = null;
                                      _viewModel.selectedBrand.value = brand;
                                      _viewModel.getTelcoDetail();
                                    },
                                  ),
                            );
                          },
                  child: Container(
                    padding: const EdgeInsets.all(4),
                    height: 48,
                    width: 64,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(8),
                      border: Border.all(color: Colors.grey.shade300),
                    ),
                    child: loadNetworkImage(
                      url: _viewModel.selectedBrand.value?.logo,
                      fit: BoxFit.fitWidth,
                      placeholderAsset: "assets/images/bg_default_169.png",
                    ),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16),
            _buildTagHistory(),
            const SizedBox(height: 8),
          ],
        ),
      );
    });
  }

  Widget _buildTagHistory() {
    final histories = _viewModel.histories;
    return Obx(() {
      return SizedBox(
        height: 36,
        child: Center(
          child: ListView.separated(
            scrollDirection: Axis.horizontal,
            padding: const EdgeInsets.symmetric(horizontal: 8),
            itemCount: histories.length,
            separatorBuilder: (_, _) => const SizedBox(width: 8),
            itemBuilder: (_, index) {
              final phone = histories[index];
              final myPhone = DataPreference.instance.phone ?? '';
              final isMyPhone = phone == myPhone;
              final selected = phone == _viewModel.phoneNumber.value;
              return GestureDetector(
                onTap: () {
                  setState(() {
                    _viewModel.phoneNumber.value = phone;
                    _phoneController.text = phone;
                    _viewModel.checkMobileNetwork();
                  });
                },
                child: Container(
                  padding: EdgeInsets.all(4),
                  decoration: BoxDecoration(
                    color: selected ? Colors.orange.shade50 : Colors.grey.shade100,
                    borderRadius: BorderRadius.circular(8),
                    border: Border.all(color: selected ? Colors.orange : Colors.grey.shade300),
                  ),
                  child: Center(
                    child: Text(
                      isMyPhone ? " Số của tôi " : " $phone ",
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        color: selected ? Colors.orange : Colors.black54,
                        fontSize: 16,
                        fontWeight: selected ? FontWeight.bold : FontWeight.normal,
                      ),
                    ),
                  ),
                ),
              );
            },
          ),
        ),
      );
    });
  }

  Future<void> pickContact(BuildContext context) async {
    try {
      final contact = await showContactPicker(context);
      if (contact == null) return;
      if (contact.phones.isEmpty) return;
      String phone = contact.phones.first.number;
      phone = phone.replaceAll(RegExp(r'[\s\-\(\)]'), '');
      _phoneController.text = phone;
      _viewModel.phoneNumber.value = phone;
      _viewModel.checkMobileNetwork();
    } catch (e) {
      debugPrint('❌ pickContact error: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Không thể truy cập danh bạ')),
      );
    }
  }
}
