import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter_widget_from_html_core/flutter_widget_from_html_core.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/app/routing/directional_action_type.dart';
import 'package:mypoint_flutter_app/core/theme/base_color.dart';
import 'package:mypoint_flutter_app/shared/navigation/directional_screen.dart';
import '../../../app/config/constants.dart';
import '../../../shared/widgets/alert/custom_alert_dialog.dart';
import '../../../shared/widgets/alert/data_alert_model.dart';
import '../../../shared/widgets/base_view/base_screen.dart';
import '../../../shared/widgets/base_view/basic_state.dart';
import '../../../shared/widgets/custom_empty_widget.dart';
import '../../../shared/widgets/custom_navigation_bar.dart';
import '../../../shared/widgets/image_loader.dart';
import '../../../shared/widgets/measure_size.dart';
import '../models/invite_friend_campaign_model.dart';
import '../referral_code_invite_friend/referral_code_invite_friend_viewmodel.dart';

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

  @override
  State<CampaignInviteReferralInfoScreen> createState() => _CampaignInviteReferralInfoScreenState();
}

class _CampaignInviteReferralInfoScreenState extends BaseState<CampaignInviteReferralInfoScreen> with BasicState {
  late final ReferralCodeInviteFriendViewModel _viewModel;
  final ValueNotifier<double> _infoHeightNotifier = ValueNotifier<double>(0);
  String? id;
  String? code;

  @override
  void initState() {
    super.initState();
    final args = Get.arguments;
    if (args is Map) {
      id = args['id'];
      code = args['code'];
    }
    _viewModel = Get.put(ReferralCodeInviteFriendViewModel());
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _viewModel.getInviteFriendCampaignDetail(id ?? '', {'invite_username': code ?? ''});
    });
    _viewModel.onShowAlertError = (message) {
      if (message.isEmpty) return;
      showAlertError(content: message);
    };
    _viewModel.acceptCampaignResponse = (data) {
      final popup = DataAlertModel(
        title: data.title ?? 'Nhận lời mời thành công',
        description: data.content ?? 'Hãy thực hiện nhiệm vụ và xem trạng thái nhận quà trong mục lịch sử',
        localHeaderImage: 'assets/images/ic_pipi_05.png',
        buttons: [
          AlertButton(
            text: 'Đóng',
            onPressed: () {
              Get.back();
            },
            bgColor: BaseColor.second300,
            textColor: Colors.white,
          ),
          AlertButton(
            text: 'Thực hiện',
            onPressed: () {
              WidgetsBinding.instance.addPostFrameCallback((_) {
                Get.back();
                data.directionalScreen?.begin();
              });
            },
            bgColor: BaseColor.primary500,
            textColor: Colors.white,
          ),
        ],
      );
      showAlert(data: popup, direction: ButtonsDirection.row);
    };
  }

  @override
  void dispose() {
    _infoHeightNotifier.dispose();
    super.dispose();
  }

  @override
  Widget createBody() {
    return Scaffold(
      backgroundColor: Colors.grey.shade100,
      appBar: PreferredSize(
        preferredSize: Size.fromHeight(kToolbarHeight + Constants.extendTopPaddingNavigation),
        child: Obx(() {
          final title = _viewModel.campaignDetail.value?.name ?? 'Chi tiết chiến dịch';
          return CustomNavigationBar(title: title);
        }),
      ),
      body: Obx(() {
        final campaign = _viewModel.campaignDetail.value;
        if (campaign == null) {
          return Center(child: EmptyWidget(isLoading: _viewModel.isLoading.value));
        }
        return Stack(
          children: [
            SingleChildScrollView(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  _buildHeaderWithInfo(campaign),
                  ValueListenableBuilder<double>(
                    valueListenable: _infoHeightNotifier,
                    builder: (_, value, _) => SizedBox(height: max(value - 24, 0)),
                  ),
                  _buildTextBlock("Phần thưởng", campaign.rewardContent),
                  _buildTextBlock("Hướng dẫn", campaign.steps?.description),
                  _buildStepList(campaign.steps?.steps),
                  Container(color: Colors.transparent, child: SizedBox(height: 64)),
                ],
              ),
            ),
          ],
        );
      }),
      bottomNavigationBar: _buildBottomAction(),
    );
  }

  Widget _buildStepList(List<CampaignStepItemInviteFriendDetailModel>? steps) {
    if (steps == null || steps.isEmpty) return const SizedBox();
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: steps.asMap().entries.map((entry) {
          final item = entry.value;
          final title = (item.title?.trim().isNotEmpty ?? false) ? item.title!.trim() : item.description?.trim();
          final description = (item.title?.trim().isNotEmpty ?? false) ? item.description?.trim() : null;
          return Container(
            width: double.infinity,
            margin: const EdgeInsets.only(top: 8),
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(16),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  title ?? '',
                  style: const TextStyle(fontSize: 12, fontWeight: FontWeight.bold, color: Colors.black87),
                ),
                const SizedBox(height: 4),
                if (description != null && description.isNotEmpty) ...[
                  const SizedBox(height: 4),
                  Text(
                    description,
                    style: const TextStyle(fontSize: 13, color: Colors.black87),
                  ),
                ],
              ],
            ),
          );
        }).toList(),
      ),
    );
  }

  Widget _buildBottomAction() {
    return _buildBottomActionContainer(
      child: SizedBox(
        width: double.infinity,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Row(
              children: [
                Expanded(
                  child: ElevatedButton(
                    onPressed: () {
                      Get.back();
                    },
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.white,
                      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
                    ),
                    child: const Padding(
                      padding: EdgeInsets.symmetric(vertical: 12),
                      child: Text(
                        'Huỷ',
                        style: TextStyle(fontSize: 16, color: Colors.black, fontWeight: FontWeight.w600),
                      ),
                    ),
                  ),
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: ElevatedButton(
                    onPressed: () {
                      final campaign = _viewModel.campaignDetail.value;
                      if (campaign == null) return;
                      _viewModel.acceptCampaign(campaign, code ?? '');
                    },
                    style: ElevatedButton.styleFrom(
                      backgroundColor: BaseColor.primary500,
                      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
                    ),
                    child: const Padding(
                      padding: EdgeInsets.symmetric(vertical: 12),
                      child: Text(
                        'Xác nhận',
                        style: TextStyle(fontSize: 16, color: Colors.white, fontWeight: FontWeight.w600),
                      ),
                    ),
                  ),
                ),
              ],
            ),
            TextButton(
              onPressed: () {
                final id = _viewModel.campaignDetail.value?.rulesId.toString() ?? '';
                if (id.isEmpty) return;
                final direction = DirectionalScreen.buildByName(name: DirectionalScreenName.website, clickActionParam: id);
                direction?.begin();
              },
              style: TextButton.styleFrom(
                backgroundColor: Colors.white,
                foregroundColor: Colors.blueAccent,
              ),
              child: const Text('Xem thể lệ', style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600)),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildBottomActionContainer({required Widget child}) {
    return Container(
      padding: const EdgeInsets.only(left: 16, right: 16, top: 12, bottom: 4),
      decoration: const BoxDecoration(
        color: Colors.white,
        boxShadow: [BoxShadow(color: Colors.black54, blurRadius: 8, offset: Offset(0, 4))],
      ),
      child: SafeArea(top: false, child: child),
    );
  }

  Widget _buildTextBlock(String title, String? content) {
    if (content == null || content.isEmpty) return const SizedBox();
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const SizedBox(height: 8),
          Text(title, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
          Container(
            width: double.infinity,
            padding: const EdgeInsets.all(16),
            margin: const EdgeInsets.only(top: 8),
            decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(16)),
            child: HtmlWidget(content, textStyle: const TextStyle(fontSize: 14, color: Colors.black87)),
          ),
        ],
      ),
    );
  }

  Widget _buildHeaderWithInfo(CampaignInviteFriendItemModel campaign) {
    final double screenWidth = MediaQuery.of(context).size.width;
    final double imageHeight = screenWidth / (16 / 9);

    return Stack(
      clipBehavior: Clip.none,
      children: [
        loadNetworkImage(
          url: campaign.bannerUrl,
          fit: BoxFit.cover,
          height: imageHeight,
          width: double.infinity,
          placeholderAsset: 'assets/images/bg_default_169.png',
        ),
        Positioned(
          left: 16,
          right: 16,
          child: MeasureSize(
            onChange: (size) {
              if (_infoHeightNotifier.value != size.height) {
                _infoHeightNotifier.value = size.height;
              }
            },
            child: Transform.translate(
              offset: Offset(0, imageHeight - 24),
              child: _buildInfo(campaign),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildInfo(CampaignInviteFriendItemModel campaign) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.1), blurRadius: 8, offset: const Offset(0, 4))],
      ),
      child: HtmlWidget(
        campaign.inviteDescription ?? '',
        textStyle: const TextStyle(fontSize: 14, color: Colors.black87),
      ),
    );
  }
}
