import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/preference/point/point_manager.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 '../../widgets/custom_empty_widget.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';
import 'models/main_section_config_model.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;
  bool _isRefreshingFlashSale = false;

  @override
  void initState() {
    super.initState();
    UserPointManager().fetchUserPoint();
    _headerHomeVM.freshData();
    runPopupCheck(DirectionalScreenName.home);
  }

  Future<void> _onFlashSaleCountdownFinished() async {
    if (_isRefreshingFlashSale) return;
    _isRefreshingFlashSale = true;
    try {
      await _viewModel.refreshFlashSale();
    } finally {
      _isRefreshingFlashSale = false;
    }
  }

  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 sections = _viewModel.sectionLayouts.map(_buildSection).whereType<Widget>().toList();
    if (sections.isEmpty) {
      return const [Padding(padding: EdgeInsets.symmetric(vertical: 40), child: EmptyWidget())];
    }
    return sections;
  }

  Widget? _buildSection(MainSectionConfigModel section) {
    switch (section.headerSectionType) {
      case HeaderSectionType.banner:
        if (_viewModel.banners.isEmpty) return null;
        return BannerCarousel(
          banners: _viewModel.banners,
          sectionConfig: _viewModel.getMainSectionConfigModel(HeaderSectionType.banner),
          onTap: (item) => item.directionalScreen?.begin(),
        );
      case HeaderSectionType.topButton:
        if (_viewModel.services.isEmpty) return null;
        return MainServiceGrid(
          services: _viewModel.services,
          sectionConfig: _viewModel.getMainSectionConfigModel(HeaderSectionType.topButton),
          onTap: (item) => item.directionalScreen?.begin(),
        );
      case HeaderSectionType.campaign:
        if (_viewModel.achievements.isEmpty) return null;
        return AchievementCarousel(
          items: _viewModel.achievements,
          sectionConfig: _viewModel.getMainSectionConfigModel(HeaderSectionType.campaign),
          onTap: (item) => item.directionScreen?.begin(),
        );
      case HeaderSectionType.product:
        if (_viewModel.products.isEmpty) return null;
        final displayProducts = List<ProductModel>.from(_viewModel.products);
        if (displayProducts.length.isOdd) {
          displayProducts.removeLast();
        }
        if (displayProducts.isEmpty) return null;
        return ProductGrid(
          products: displayProducts,
          sectionConfig: _viewModel.getMainSectionConfigModel(HeaderSectionType.product),
          onTap: (product) => Get.toNamed(voucherDetailScreen, arguments: product.id),
        );
      case HeaderSectionType.news:
        if (_viewModel.news.isEmpty) return null;
        return NewsCarouselWidget(
          items: _viewModel.news,
          sectionConfig: _viewModel.getMainSectionConfigModel(HeaderSectionType.news),
          onTap: (item) => Get.toNamed(campaignDetailScreen, arguments: {"id": item.pageId}),
        );
      case HeaderSectionType.myProduct:
        if (_viewModel.myProducts.isEmpty) return null;
        return MyProductCarouselWidget(
          items: _viewModel.myProducts,
          sectionConfig: _viewModel.getMainSectionConfigModel(HeaderSectionType.myProduct),
          onTap: (item) => Get.toNamed(voucherDetailScreen, arguments: {"customerProductId": item.id}),
        );
      case HeaderSectionType.flashSale:
        final products = _viewModel.flashSaleData.value?.products ?? [];
        if (products.isEmpty) return null;
        return FlashSaleCarouselWidget(
          products: products,
          sectionConfig: _viewModel.getMainSectionConfigModel(HeaderSectionType.flashSale),
          onTap: (product) => Get.toNamed(voucherDetailScreen, arguments: product.id),
          onCountdownFinished: _onFlashSaleCountdownFinished,
        );
      case HeaderSectionType.brand:
        if (_viewModel.brands.isEmpty) return null;
        return BrandGridWidget(
          brands: _viewModel.brands,
          sectionConfig: _viewModel.getMainSectionConfigModel(HeaderSectionType.brand),
          onTap: (_) {},
        );
      case HeaderSectionType.pointPartner:
        if (_viewModel.affiliates.isEmpty) return null;
        return AffiliateBrandGridWidget(
          affiliateBrands: _viewModel.affiliates,
          sectionConfig: _viewModel.getMainSectionConfigModel(HeaderSectionType.pointPartner),
          onTap: (_) {},
        );
      default:
        return null;
    }
  }

  @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: const AlwaysScrollableScrollPhysics(),
            headerSliverBuilder: (_, _) => [_buildSliverHeader(heightHeader)],
            body: RefreshIndicator(
              onRefresh: _onRefresh,
              child: Obx(() {
                return ListView(
                  padding: EdgeInsets.only(bottom: paddingBottom),
                  physics: const 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(showLoading: false);
    await _viewModel.loadDataPiPiHome();
    await _headerHomeVM.freshData();
  }
}
