import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/widgets/custom_empty_widget.dart';
import '../../base/base_screen.dart';
import '../../base/basic_state.dart';
import '../../resources/base_color.dart';
import '../../widgets/bottom_sheet_helper.dart';
import '../home/custom_widget/hover_view_widget.dart';
import 'campaign_7day_guide_dialog.dart';
import 'campaign_7day_mission_info_dialog.dart';
import 'campaign_7day_reward_dialog.dart';
import 'campaign_7day_viewmodel.dart';
import 'custom_widgets/campaign_7day_marguee_bar.dart';
import 'custom_widgets/campaign_7day_mission_card_item.dart';
import 'custom_widgets/campaign_7day_progress_box.dart';
import 'custom_widgets/campaign_7day_special_misssion_card.dart';
import 'custom_widgets/campaign_7day_top_buttons.dart';

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

  @override
  State<Campaign7DayScreen> createState() => _Campaign7DayScreenState();
}

class _Campaign7DayScreenState extends BaseState<Campaign7DayScreen> with BasicState {
  late final Campaign7DayViewModel _viewModel;

  @override
  void initState() {
    super.initState();
    String? campaignId = '1';
    final args = Get.arguments;
    if (args is String) {
      campaignId = args;
    }
    if (campaignId == null) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        Get.back();
      });
      return;
    }
    _viewModel = Get.put(Campaign7DayViewModel(campaignId: campaignId));
    _viewModel.getLiveTransactions();
    _viewModel.getCampaign7DayInfo();
    _viewModel.onShowAlertError = (message, onBack) {
      if (message.isEmpty) return;
      showAlertError(
          content: message,
          showCloseButton: !onBack,
          onConfirmed: () {
            if (onBack) Get.back();
          });
    };
    _viewModel.submitPerformMissionResponse = (mission) {
      final popup = mission.popup;
      if (popup != null) {
        showAlert(data: popup.dataAlertModel);
      }
    };
    _viewModel.getCampaignRewardsResponse = (rewards) {
      BottomSheetHelper.showBottomSheetPopup(
        backgroundContainerColor: Colors.transparent,
        horizontalContainerPadding: 0,
        child: Campaign7DayRewardDialog(
          rewards: rewards,
          onClose: () {
            Get.back();
          },
        ),
      );
    };
  }

  @override
  Widget createBody() {
    return Scaffold(
      body: Stack(
        children: [
          RefreshIndicator(
            onRefresh: () async {
              _viewModel.getLiveTransactions();
              _viewModel.getCampaign7DayInfo();
            },
            child: SingleChildScrollView(
              physics: const AlwaysScrollableScrollPhysics(),
              child: Column(
                children: [
                  _buildHeaderWithInfo(),
                  const SizedBox(height: 88),
                  Obx(() => _buildMissionList()),
                  const SizedBox(height: 24),
                ],
              ),
            ),
          ),
          Campaign7dayTopButtons(
            onBack: () {
              Get.back();
            },
            onInfo: () {
              BottomSheetHelper.showBottomSheetPopup(
                backgroundContainerColor: Colors.transparent,
                horizontalContainerPadding: 0,
                bottomContainerPadding: 0,
                child: Campaign7DayGuideDialog(
                  title: _viewModel.campaign7DayInfo.value?.name ?? 'Chiến dịch 7 ngày',
                  htmlContent: _viewModel.campaign7DayInfo.value?.description ?? '',
                  onClose: () {
                    Get.back();
                  },
                ),
              );
            },
            onGift: () {
              _viewModel.getCampaignRewards();
            },
          ),
          Positioned.fill(
            child: Obx(()
              // print('_viewModel.campaign7DayInfo.value?.countDownTime: ${_viewModel.campaign7DayInfo.value?.countDownTime}');
              => HoverView(
                imagePath: _viewModel.campaign7DayInfo.value?.config?.mainIcon ?? 'assets/images/ic_pipi_04.png',
                onTap: null,
                onClose: null,
                backgroundColor: Colors.transparent,
                size: 80,
                countDownTime: _viewModel.campaign7DayInfo.value?.countDownTime ?? 0.0,
              ),
            ),
          ),
        ],
      ),
      backgroundColor: BaseColor.primary400,
    );
  }

  Widget _buildHeaderWithInfo() {
    final heightImageBG = MediaQuery.of(context).size.width * 1589 / 1125;
    return Stack(
      clipBehavior: Clip.none,
      children: [
        Image.asset(
          'assets/images/bg_campaign_7day.png',
          fit: BoxFit.fill,
          width: double.infinity,
          height: heightImageBG,
        ),
        Positioned(
          left: 16,
          right: 16,
          child: Transform.translate(
            offset: Offset(0, heightImageBG - 90),
            child: Obx(() {
              final text = _viewModel.liveTransactions.value;
              final missions = _viewModel.campaign7DayInfo.value?.missions ?? [];
              return Column(
                children: [
                  if (text.isNotEmpty) CampaignMarqueeNoticeBar(text: text.join('   •   ')),
                  const SizedBox(height: 14),
                  if (missions.isNotEmpty) Campaign7DayProgressBox(missions: missions),
                  const SizedBox(height: 16),
                ],
              );
            }),
          ),
        ),
      ],
    );
  }

  Widget _buildMissionList() {
    final missions = _viewModel.campaign7DayInfo.value?.missions ?? [];
    if (missions.isEmpty) {
      return const Center(child: EmptyWidget(content: 'Không có nhiệm vụ nào'));
    }
    final normalMissions = missions.where((mission) => !mission.isSpecial).toList();
    final specialMissions = missions.where((mission) => mission.isSpecial).toList();
    return Stack(
      clipBehavior: Clip.none,
      children: [
        Container(
          margin: const EdgeInsets.only(top: 9, left: 16, right: 16), // để chừa chỗ ảnh header
          padding: const EdgeInsets.all(12),
          decoration: BoxDecoration(color: Color(0xFFFEF1F2), borderRadius: BorderRadius.circular(16)),
          child: Column(
            children: [
              const SizedBox(height: 30),
              ...normalMissions.map(
                (mission) => Campaign7DayMissionCardItem(
                  mission: mission,
                  onTapInfo: () {
                    BottomSheetHelper.showBottomSheetPopup(
                      backgroundContainerColor: Colors.transparent,
                      child: Campaign7DayMissionInfoDialog(
                        mission: mission,
                        onConfirm: () {
                          Get.back();
                          _viewModel.submitPerformMission(mission);
                        },
                        onClose: () {
                          Get.back();
                        },
                      ),
                    );
                  },
                  onTapClaimReward: () {
                    _viewModel.submitPerformMission(mission);
                  },
                ),
              ),
              if (specialMissions.isNotEmpty)
                ...specialMissions.map(
                  (mission) => Campaign7DaySpecialMissionCard(
                    mission: mission,
                    onTap: () {
                      _viewModel.submitPerformMission(mission);
                    },
                  ),
                ),
            ],
          ),
        ),
        Positioned(
          top: 0,
          left: 0,
          right: 0,
          child: Center(
            child: Stack(
              alignment: Alignment.center,
              children: [
                Image.asset('assets/images/ic_header_alert_campaign.png', height: 48, fit: BoxFit.contain),
                const Text(
                  'Danh sách nhiệm vụ',
                  style: TextStyle(
                    color: Colors.white,
                    fontWeight: FontWeight.w800,
                    fontSize: 17,
                    shadows: [Shadow(color: Colors.black26, offset: Offset(2, 2), blurRadius: 2)],
                  ),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }
}
