import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/screen/voucher/voucher_list/voucher_list_screen.dart';
import '../../shared/router_gage.dart';
import 'voucher_tab_viewmodel.dart';
import 'sub_widget/voucher_action_menu.dart';
import 'sub_widget/voucher_item_grid.dart';
import 'sub_widget/voucher_item_list.dart';
import 'sub_widget/voucher_section_title.dart';
import '../../widgets/custom_navigation_bar.dart';

class VoucherTabScreen extends StatelessWidget {
  const VoucherTabScreen({super.key});

  @override
  Widget build(BuildContext context) {
    final VoucherTabViewModel viewModel = Get.put(VoucherTabViewModel());

    return Scaffold(
      appBar: CustomNavigationBar(
        title: "Ưu đãi",
        showBackButton: false,
        rightButtons: [
          IconButton(
            icon: const Icon(Icons.search, color: Colors.white),
            onPressed: () {
              Get.toNamed(vouchersScreen, arguments: {"enableSearch": true});
            },
          ),
        ],
      ),
      body: Obx(() {
        if (viewModel.isLoading.value) {
          return const Center(child: CircularProgressIndicator());
        }
        return RefreshIndicator(
          onRefresh: viewModel.refreshData,
          child: NotificationListener<ScrollNotification>(
            onNotification: (ScrollNotification scrollInfo) {
              if (scrollInfo is ScrollUpdateNotification &&
                  scrollInfo.metrics.axis == Axis.vertical && // ✅ Chỉ check vertical
                  !viewModel.isLoadMore.value &&
                  viewModel.hasMore &&
                  scrollInfo.metrics.pixels >=
                      scrollInfo.metrics.maxScrollExtent - 200) {
                viewModel.getAllProducts();
              }
              return false;
            },
            child: ListView(
              physics: const AlwaysScrollableScrollPhysics(),
              children: [
                const VoucherSectionTitle(title: 'Ưu đãi từ nhà mạng'),
                const VoucherActionMenu(),
                VoucherSectionTitle(
                  title: 'Săn ưu đãi',
                  onViewAll: () {
                    Get.toNamed(vouchersScreen, arguments: {"isHotProduct": true});
                  },
                ),
                VoucherItemGrid(items: viewModel.hotProducts),
                const VoucherSectionTitle(title: 'Tất cả ưu đãi'),
                VoucherItemList(items: viewModel.allProducts),
                if (viewModel.isLoadMore.value)
                  const Padding(
                    padding: EdgeInsets.symmetric(vertical: 16),
                    child: Center(child: CircularProgressIndicator()),
                  ),
              ],
            ),
          ),
        );
      }),
    );
  }
}
