import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:mypoint_flutter_app/core/utils/extensions/string_extension.dart';
import 'package:mypoint_flutter_app/features/topup/topup_viewmodel.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 '../../core/theme/base_color.dart';
import '../../shared/router_gage.dart';
import '../contacts/contacts_picker.dart';
import 'brand_select_sheet_widget.dart';


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

  @override
  State<PhoneTopUpScreen> createState() => _PhoneTopUpScreenState();
}

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

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

  String get formattedAmount {
    return NumberFormat.currency(
      locale: 'vi_VN',
      symbol: '',
      decimalDigits: 0,
    ).format(_viewModel.selectedProduct.value?.amountToBePaid ?? 0);
  }

  @override
  Widget createBody() {
    return Scaffold(
      appBar: CustomNavigationBar(title: "Nạp tiền điện thoại"),
      body: Obx(() {
        return Column(
          children: [
            _buildHeaderPhone(),
            Container(height: 6, color: Colors.grey.shade200),
            const Divider(height: 8),
            _buildItemTypeProduct(),
            const Divider(height: 1),
          ],
        );
      }),
      bottomNavigationBar: Obx(() {
        return _buildBottomAction();
      }),
    );
  }

  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.trim();
                      _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.trim();
                    _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,
                      ),
                    ),
                  ),
                ),
              );
            },
          ),
        ),
      );
    });
  }

  Widget _buildItemTypeProduct() {
    return Expanded(
      child: SingleChildScrollView(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text("Mệnh giá", style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16)),
            const SizedBox(height: 12),
            GridView.count(
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              crossAxisCount: 2,
              crossAxisSpacing: 12,
              mainAxisSpacing: 12,
              childAspectRatio: 3,
              children:
                  _viewModel.products.value.map((product) {
                    final isSelected = product.id == _viewModel.selectedProduct.value?.id;
                    final preview = product.previewCampaign;

                    return GestureDetector(
                      onTap: () => setState(() => _viewModel.selectedProduct.value = product),
                      child: Container(
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(12),
                          border: Border.all(color: isSelected ? Colors.orange : Colors.grey.shade300),
                          color: isSelected ? Colors.orange.withOpacity(0.1) : Colors.white,
                        ),
                        child: Stack(
                          children: [
                            // Gift icon
                            if (preview?.hasGift == true)
                              Positioned(
                                top: 8,
                                left: 0,
                                child: Image.asset('assets/images/ic_mark_give_voucher.png', height: 16),
                              ),
                            // Point icon
                            if ((preview?.rewardPoint ?? 0) > 0)
                              Positioned(
                                top: 0,
                                right: 8,
                                child: Image.asset('assets/images/ic_mark_give_point.png', width: 24),
                              ),
                            // Text center
                            Center(
                              child: Text(
                                "${NumberFormat.currency(locale: 'vi_VN', symbol: '', decimalDigits: 0).format(product.amountToBePaid ?? 0)}đ",
                                style: TextStyle(
                                  fontWeight: FontWeight.bold,
                                  fontSize: 14,
                                  color: isSelected ? Colors.orange : Colors.black87,
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    );
                  }).toList(),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildBottomAction() {
    final product = _viewModel.selectedProduct.value;
    final preview = product?.previewCampaign;
    final rewardPoint = preview?.rewardPoint ?? 0;
    final hasGift = preview?.hasGift == true;

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
      decoration: const BoxDecoration(
        color: Colors.white,
        boxShadow: [BoxShadow(color: Colors.black54, blurRadius: 8, offset: Offset(0, 4))],
      ),
      child: SafeArea(
        top: false,
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
          color: Colors.white,
          child: Row(
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: [
                  Row(
                    children: [
                      Text("Tổng: ", style: TextStyle(color: Colors.grey.shade600, fontSize: 16)),
                      Text(
                        "$formattedAmountđ",
                        style: const TextStyle(color: BaseColor.primary500, fontWeight: FontWeight.bold, fontSize: 20),
                      ),
                    ],
                  ),
                  const SizedBox(height: 4),
                  Row(
                    children: [
                      if (rewardPoint > 0)
                        Row(
                          children: [
                            Text(
                              "+",
                              style: const TextStyle(color: Colors.orange, fontSize: 16, fontWeight: FontWeight.bold),
                            ),
                            const SizedBox(width: 2),
                            Image.asset('assets/images/ic_point.png', width: 16, height: 16, fit: BoxFit.cover),
                            const SizedBox(width: 2),
                            Text(
                              NumberFormat.decimalPattern('vi_VN').format(rewardPoint),
                              style: const TextStyle(color: Colors.orange, fontSize: 16, fontWeight: FontWeight.bold),
                            ),
                          ],
                        ),
                      if (rewardPoint > 0 && hasGift) const SizedBox(width: 12),
                      if (hasGift)
                        Row(
                          children: [
                            Text(
                              "+",
                              style: const TextStyle(color: Colors.red, fontSize: 16, fontWeight: FontWeight.bold),
                            ),
                            SizedBox(width: 2),
                            Image.asset('assets/images/ic_gift_red.png', width: 16, height: 16, fit: BoxFit.cover),
                          ],
                        ),
                    ],
                  ),
                ],
              ),
              const Spacer(),
              ElevatedButton(
                onPressed: _viewModel.phoneNumber.value.isPhoneValid() ? () {
                  Get.toNamed(
                    transactionDetailScreen,
                    arguments: {"product": product, "quantity": 1, "targetPhoneNumber": _viewModel.phoneNumber.value},
                  );
                } : null,
                style: ElevatedButton.styleFrom(
                  backgroundColor: BaseColor.primary500,
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                ),
                child: const Padding(
                  padding: EdgeInsets.symmetric(horizontal: 16, vertical: 10),
                  child: Text(
                    "Nạp ngay",
                    style: TextStyle(fontSize: 16, color: Colors.white, fontWeight: FontWeight.bold),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  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.trim();
      _viewModel.checkMobileNetwork();
    } catch (e) {
      debugPrint('❌ pickContact error: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Không thể truy cập danh bạ')),
      );
    }
  }
}
