import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/screen/home/custom_widget/header_home_widget.dart';
import 'package:mypoint_flutter_app/screen/home/custom_widget/product_grid_widget.dart';
import 'package:mypoint_flutter_app/screen/pipi/pipi_detail_screen.dart';
import 'package:mypoint_flutter_app/screen/voucher/models/product_model.dart';
import 'package:mypoint_flutter_app/shared/router_gage.dart';
import '../../directional/directional_action_type.dart';
import '../popup_manager/popup_runner_helper.dart';
import 'custom_widget/achievement_carousel_widget.dart';
import 'custom_widget/affiliate_brand_grid_widget.dart';
import 'custom_widget/banner_carousel_widget.dart';
import 'custom_widget/brand_grid_widget.dart';
import 'custom_widget/flash_sale_carousel_widget.dart';
import 'custom_widget/hover_view_widget.dart';
import 'custom_widget/main_service_grid_widget.dart';
import 'custom_widget/my_product_carousel_widget.dart';
import 'custom_widget/news_carousel_widget.dart';
import 'header_home_viewmodel.dart';
import 'home_tab_viewmodel.dart';
import 'models/header_section_type.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> with PopupOnInit {
  final HomeTabViewModel _viewModel = Get.put(HomeTabViewModel());
  final _headerHomeVM = Get.find<HeaderHomeViewModel>();
  final RxBool _showHover = true.obs;

  @override
  void initState() {
    super.initState();
    runPopupCheck(DirectionalScreenName.home);
  }

  Widget _buildSliverHeader(double heightHeader) {
    return Obx(() {
      final notifyUnreadData = _headerHomeVM.notificationUnreadData.value;
      return SliverToBoxAdapter(
        child: HomeGreetingHeader(
          dataHeader: _headerHomeVM.headerData,
          heightContent: heightHeader,
          notificationUnreadData: notifyUnreadData,
        ),
      );
    });
  }

  List<Widget> _buildSectionContent() {
    final List<Widget> sections = [];
    for (var section in _viewModel.sectionLayouts.value) {
      switch (section.headerSectionType) {
        case HeaderSectionType.banner:
          if (_viewModel.banners.isNotEmpty) {
            sections.add(
              BannerCarousel(
                banners: _viewModel.banners,
                sectionConfig: _viewModel.getMainSectionConfigModel(HeaderSectionType.banner),
                onTap: (item) {
                  item.directionalScreen?.begin();
                },
              ),
            );
          }
          break;
        case HeaderSectionType.topButton:
          if (_viewModel.services.isNotEmpty) {
            sections.add(
              MainServiceGrid(
                services: _viewModel.services,
                sectionConfig: _viewModel.getMainSectionConfigModel(HeaderSectionType.topButton),
                onTap: (item) {
                  item.directionalScreen?.begin();
                },
              ),
            );
          }
          break;
        case HeaderSectionType.campaign:
          if (_viewModel.achievements.isNotEmpty) {
            sections.add(
              AchievementCarousel(
                items: _viewModel.achievements,
                sectionConfig: _viewModel.getMainSectionConfigModel(HeaderSectionType.campaign),
                onTap: (item) {
                  item.directionScreen?.begin();
                },
              ),
            );
          }
          break;
        case HeaderSectionType.product:
          if (_viewModel.products.isNotEmpty) {
            List<ProductModel> products = _viewModel.products;
            final length = products.length;
            products = (length.isOdd) ? products.sublist(0, length - 1) : products;
            sections.add(
              ProductGrid(
                products: products,
                sectionConfig: _viewModel.getMainSectionConfigModel(HeaderSectionType.product),
                onTap: (product) {
                  Get.toNamed(voucherDetailScreen, arguments: product.id);
                },
              ),
            );
          }
          break;
        case HeaderSectionType.news:
          if (_viewModel.news.isNotEmpty) {
            sections.add(
              NewsCarouselWidget(
                items: _viewModel.news,
                sectionConfig: _viewModel.getMainSectionConfigModel(HeaderSectionType.news),
                onTap: (item) async {
                  Get.toNamed(campaignDetailScreen, arguments: {"id": item.pageId});
                },
              ),
            );
          }
          break;
        case HeaderSectionType.myProduct:
          if (_viewModel.myProducts.isNotEmpty) {
            sections.add(
              MyProductCarouselWidget(
                items: _viewModel.myProducts,
                sectionConfig: _viewModel.getMainSectionConfigModel(HeaderSectionType.myProduct),
                onTap: (item) async {
                  Get.toNamed(voucherDetailScreen, arguments: {"customerProductId": item.id});
                },
              ),
            );
          }
          break;
        case HeaderSectionType.flashSale:
          final products = _viewModel.flashSaleData.value?.products ?? [];
          if (products.isNotEmpty) {
            sections.add(
              FlashSaleCarouselWidget(
                products: products,
                sectionConfig: _viewModel.getMainSectionConfigModel(HeaderSectionType.flashSale),
                onTap: (product) {
                  Get.toNamed(voucherDetailScreen, arguments: product.id);
                },
              ),
            );
          }
          break;
        case HeaderSectionType.brand:
          if (_viewModel.brands.isNotEmpty) {
            sections.add(
              BrandGridWidget(
                brands: _viewModel.brands,
                sectionConfig: _viewModel.getMainSectionConfigModel(HeaderSectionType.brand),
                onTap: (item) {
                  // Get.toNamed(affiliateDetailScreen, arguments: item.brandId);
                },
              ),
            );
          }
          break;
        case HeaderSectionType.pointPartner:
          if (_viewModel.affiliates.isNotEmpty) {
            sections.add(
              AffiliateBrandGridWidget(
                affiliateBrands: _viewModel.affiliates,
                sectionConfig: _viewModel.getMainSectionConfigModel(HeaderSectionType.pointPartner),
                onTap: (item) {
                  // Get.toNamed(affiliateDetailScreen, arguments: item.brandId);
                },
              ),
            );
          }
          break;
        default:
          break;
      }
    }
    return sections;
  }

  @override
  Widget build(BuildContext context) {
    final paddingBottom = MediaQuery.of(context).padding.bottom + 20;
    final width = MediaQuery.of(context).size.width;
    final heightHeader = width * 86 / 375 + 112;
    return Scaffold(
      body: Stack(
        children: [
          NestedScrollView(
            physics: AlwaysScrollableScrollPhysics(),
            headerSliverBuilder: (_, _) => [_buildSliverHeader(heightHeader)],
            body: RefreshIndicator(
              onRefresh: _onRefresh,
              child: Obx(() {
                return ListView(
                  padding: EdgeInsets.only(bottom: paddingBottom),
                  physics: AlwaysScrollableScrollPhysics(),
                  children: _buildSectionContent(),
                );
              }),
            ),
          ),
          Obx(() {
            if (!_showHover.value) return SizedBox.shrink();
            return HoverView(
              imagePath: _viewModel.hoverData.value?.icon ?? '',
              onTap: _handleHoverViewTap,
              onClose: _handleCloseHoverView,
              backgroundColor: Colors.transparent,
              size: 80,
              countDownTime: _viewModel.hoverData.value?.countDownTime ?? 0.0,
            );
          }),
        ],
      ),
    );
  }

  void _handleHoverViewTap() {
    final result = _viewModel.hoverData.value?.direction?.begin();
    if (result != true) {
      showModalBottomSheet(
        context: context,
        backgroundColor: Colors.transparent,
        isScrollControlled: true,
        builder: (_) => PipiDetailScreen(),
      );
    }
  }

  void _handleCloseHoverView() {
    setState(() {
      _showHover.value = false;
    });
  }

  Future<void> _onRefresh() async {
    await _viewModel.getSectionLayoutHome();
    await _viewModel.loadDataPiPiHome();
    await _headerHomeVM.freshData();
  }
}
