import 'dart:async';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../base/base_screen.dart';
import '../../../base/basic_state.dart';
import '../../../configs/constants.dart';
import '../../../shared/router_gage.dart';
import '../../../widgets/custom_empty_widget.dart';
import '../../../widgets/custom_navigation_bar.dart';
import '../../../widgets/custom_search_navigation_bar.dart';
import '../sub_widget/voucher_item_list.dart';
import 'voucher_list_viewmodel.dart';

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

  @override
  _VoucherListScreenState createState() => _VoucherListScreenState();
}

class _VoucherListScreenState extends BaseState<VoucherListScreen> with BasicState {
  late final Map<String, dynamic> args;
  late final bool enableSearch;
  late final bool isHotProduct;
  late final bool isFavorite;
  late final VoucherListViewModel _viewModel;
  int _remainingSeconds = 0;
  Timer? _countdownTimer;
  bool _countdownStartedEver = false; // chỉ để đảm bảo start lần đầu sau khi load xong

  @override
  void initState() {
    super.initState();
    args = Get.arguments ?? {};
    enableSearch = args['enableSearch'] ?? false;
    isHotProduct = args['isHotProduct'] ?? false;
    isFavorite = args['favorite'] ?? false;
    _viewModel = Get.put(VoucherListViewModel(isHotProduct: isHotProduct, isFavorite: isFavorite));
    _remainingSeconds = args['countDownSecond'] ?? 0;
    _viewModel.submitCampaignViewVoucherResponse = (response) {
      final popup = response.data?.popup;
      if (popup != null) {
        showPopup(data: popup);
      } else {
        showAlertError(content: response.errorMessage ?? Constants.commonError);
      }
    };

    // Bắt đầu countdown sau khi lần đầu load xong và có data, không khởi tạo từ build()
    ever<bool>(_viewModel.firstLoadDone, (done) {
      if (done && !_countdownStartedEver && _remainingSeconds > 0) {
        _startCountdownIfNeeded();
      }
    });
  }


  @override
  void onRouteWillDisappear() {
    super.onRouteWillDisappear();
    // Pause timer khi route bị che phủ (push sang màn hình khác)
    _pauseCountdown();
  }

  @override
  void onRouteDidAppear() {
    super.onRouteDidAppear();
    // Resume timer khi route trở lại visible
    _resumeCountdownIfNeeded();
  }

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

  void _startCountdownIfNeeded() {
    if (_countdownStartedEver) return; // ensure only first start after load
    if (_remainingSeconds <= 0) return;
    if (_countdownTimer != null) return; // already running
    _countdownStartedEver = true;
    _countdownTimer = Timer.periodic(const Duration(seconds: 1), (t) {
      if (!mounted) return;
      setState(() {
        _remainingSeconds -= 1;
        if (_remainingSeconds <= 0) {
          _viewModel.submitCampaignViewVoucherComplete();
          _countdownTimer?.cancel();
          _countdownTimer = null;
        }
      });
    });
  }

  void _resumeCountdownIfNeeded() {
    if (_remainingSeconds <= 0) return;
    if (_countdownTimer != null) return;
    // không đụng tới _countdownStartedEver để vẫn giữ logic chỉ start lần đầu thông qua ViewModel
    _countdownTimer = Timer.periodic(const Duration(seconds: 1), (t) {
      if (!mounted) return;
      setState(() {
        _remainingSeconds -= 1;
        if (_remainingSeconds <= 0) {
          _viewModel.submitCampaignViewVoucherComplete();
          _countdownTimer?.cancel();
          _countdownTimer = null;
        }
      });
    });
  }

  void _pauseCountdown() {
    _countdownTimer?.cancel();
    _countdownTimer = null;
  }

  @override
  Widget createBody() {
    final String title = isFavorite ? 'Yêu thích' : (isHotProduct ? 'Săn ưu đãi' : 'Tất cả ưu đãi');
    return Scaffold(
      appBar:
          enableSearch
              ? CustomSearchNavigationBar(onSearchChanged: _viewModel.onSearchChanged)
              : CustomNavigationBar(title: title),
      body: Stack(
        children: [
          Column(
            children: [
              if (enableSearch)
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                  child: Obx(() {
                    final resultCount = _viewModel.totalResult.value;
                    final displayText = _viewModel.searchQuery.isNotEmpty ? '$title ($resultCount kết quả)' : title;
                    return Align(
                      alignment: Alignment.centerLeft,
                      child: Text(displayText, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600)),
                    );
                  }),
                ),
              Expanded(
                child: Obx(() {
                   if (_viewModel.products.isEmpty) {
                    return const Center(child: EmptyWidget());
                  }
                   // Countdown start được điều phối ở initState qua ever(isLoading)
                  return RefreshIndicator(
                    onRefresh: () => _viewModel.loadData(reset: true),
                    child: ListView.builder(
                      physics: const AlwaysScrollableScrollPhysics(),
                      itemCount: _viewModel.products.length + (_viewModel.hasMore ? 1 : 0),
                      itemBuilder: (context, index) {
                        if (index >= _viewModel.products.length) {
                          _viewModel.loadData(reset: false);
                          return const Center(
                            child: Padding(padding: EdgeInsets.all(16), child: CircularProgressIndicator()),
                          );
                        }
                        final product = _viewModel.products[index];
                        return GestureDetector(
                          onTap: () async {
                            await Get.toNamed(voucherDetailScreen, arguments: {"productId": product.id});
                            _viewModel.loadData(reset: true);
                          },
                          child: VoucherListItem(product: product),
                        );
                      },
                    ),
                  );
                }),
              ),
            ],
          ),
           if (_remainingSeconds > 0)
            Positioned(
              right: 12,
              bottom: 44,
               child: Stack(
                children: [
                  Image.asset(
                    'assets/images/ic_count_down_time_voucher.png',
                    width: 90,
                    height: 90,
                    fit: BoxFit.contain,
                  ),
                  Positioned(
                    bottom: 4,
                    right: 0,
                    left: 0,
                    child: Center(
                      child: Text(
                        'Còn ${_remainingSeconds}s',
                        style: const TextStyle(color: Colors.white, fontWeight: FontWeight.w600, fontSize: 12),
                      ),
                    ),
                  ),
                ],
              ),
            ),
        ],
      ),
    );
  }
}
