import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/shared/navigation/directional_screen.dart';
import '../../features/home/custom_widget/header_home_widget.dart';
import '../../features/home/custom_widget/product_grid_widget.dart';
import '../../features/pipi/pipi_detail_screen.dart';
import '../../features/voucher/models/product_model.dart';
import '../../shared/router_gage.dart';
import '../../shared/widgets/base_view/base_screen.dart';
import '../../shared/widgets/base_view/basic_state.dart';
import '../../app/routing/directional_action_type.dart';
import '../../shared/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/hover_data_model.dart';
import 'models/main_section_config_model.dart';

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

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

class _HomeScreenState extends BaseState<HomeScreen> with PopupOnInit, BasicState {
  final HomeTabViewModel _viewModel = Get.put(HomeTabViewModel());
  final _headerHomeVM = Get.find<HeaderHomeViewModel>();
  final RxBool _showHover = false.obs;
  late final Worker _hoverDataWorker;
  bool _isRefreshingFlashSale = false;

  @override
  void initState() {
    super.initState();
    debugPrint('HomeScreen initState');
    // UserPointManager().fetchUserPoint();
    _hoverDataWorker = ever<HoverDataModel?>(_viewModel.hoverData, _onHoverDataChanged);
    _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 [
        Padding(
          padding: const EdgeInsets.symmetric(vertical: 40),
          child: EmptyWidget(isLoading: _viewModel.isLoading.value),
        ),
      ];
    }
    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: (data) {
            Get.toNamed(affiliateBrandDetailScreen, arguments: {"brandId": data.brandId});
          },
        );
      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 createBody() {
    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 direction = DirectionalScreen.buildByName(name: DirectionalScreenName.campaignSevenDayScreen, clickActionParam: "0");
    // direction?.begin();
    final result = _viewModel.hoverData.value?.direction?.begin();
    if (result != true) {
      showModalBottomSheet(
        context: context,
        backgroundColor: Colors.transparent,
        isScrollControlled: true,
        builder: (_) => PipiDetailScreen(),
      );
    }
  }

  void _handleCloseHoverView() {
    _handleCloseHoverViewInternal();
  }

  void _handleCloseHoverViewInternal({bool dismissedByUser = true}) {
    if (dismissedByUser) {
      _viewModel.hoverDismissed = true;
    }
    if (mounted) {
      _showHover.value = false;
    }
  }

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

  @override
  void onDispose() {
    _hoverDataWorker.dispose();
    _pauseCountdown();
    super.onDispose();
  }

  @override
  void onRouteWillDisappear() {
    super.onRouteWillDisappear();
    _pauseCountdown();
  }

  @override
  void onRouteDidAppear() {
    super.onRouteDidAppear();
    _headerHomeVM.fetchNotificationUnread();
    if (_viewModel.hoverDismissed) return;
    _viewModel.loadDataPiPiHome();
  }

  void _pauseCountdown() {
    _handleCloseHoverViewInternal(dismissedByUser: false);
  }

  void _resetHoverViewState() {
    _viewModel.hoverDismissed = false;
    _updateHoverVisibility();
  }

  void _updateHoverVisibility() {
    if (_viewModel.hoverDismissed || !mounted) return;
    _showHover.value = _shouldShowHover(_viewModel.hoverData.value);
  }

  void _onHoverDataChanged(HoverDataModel? data) {
    if (_viewModel.hoverDismissed || !mounted) return;
    _showHover.value = _shouldShowHover(data);
  }

  bool _shouldShowHover(HoverDataModel? data) {
    if (data == null) return false;
    return data.icon?.isNotEmpty == true;
  }
}
