import 'package:flutter/material.dart';
import 'package:flutter_widget_from_html/flutter_widget_from_html.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/widgets/custom_empty_widget.dart';
import 'package:share_plus/share_plus.dart';
import '../../base/base_screen.dart';
import '../../base/basic_state.dart';
import '../../extensions/string_extension.dart';
import '../../resources/base_color.dart';
import '../../shared/router_gage.dart';
import '../../widgets/back_button.dart';
import '../../widgets/network_image_with_aspect_ratio.dart';
import 'campaign_detail_viewmodel.dart';
import 'campaign_item_page_widget.dart';
import 'model/campaign_detail_item_model.dart';
import 'model/campaign_detail_model.dart';
import 'model/detail_page_rule_type.dart';
import 'model/media_type_item_campaign.dart';

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

  @override
  State<CampaignDetailScreen> createState() => _CampaignDetailScreenState();
}

class _CampaignDetailScreenState extends BaseState<CampaignDetailScreen> with BasicState {
  final CampaignDetailViewModel _viewModel = Get.put(CampaignDetailViewModel());

  @override
  void initState() {
    super.initState();
    _viewModel.onShowAlertError = (message) {
      if (message.isEmpty) return;
      WidgetsBinding.instance.addPostFrameCallback((_) {
        showAlertError(content: message);
      });
    };
    DetailPageRuleType? type;
    String? pageId;
    final args = Get.arguments;
    if (args is Map) {
      type = args['type'];
      pageId = args['id'];
    }
    _viewModel.fetchData(type, pageId);
  }

  @override
  Widget createBody() {
    return Scaffold(
      backgroundColor: BaseColor.second200,
      body: Obx(() {
        CampaignDetailModel? pageDetail = _viewModel.campaignDetail.value?.pageDetail;
        if (pageDetail == null) {
          return Stack(
            children: [
              const Center(child: EmptyWidget()),
              Positioned(top: MediaQuery
                  .of(context)
                  .padding
                  .top + 8, left: 8, child: CustomBackButton()),
            ],
          );
        }
        final thumbnail = pageDetail.thumbnail ?? "";
        final publishDate = pageDetail.publishDate ?? "";
        final title = pageDetail.title ?? "";
        final List<CampaignDetailItemModel> items = pageDetail.items ?? [];
        final buttonOn = pageDetail.buttonOn ?? "0";
        final heightContainerBottomButton = MediaQuery.of(context).padding.bottom + 16 + 48;
        final showShareButton = (pageDetail.shareContent ?? '').isNotEmpty;
        return Stack(
          children: [
            SingleChildScrollView(
              padding: EdgeInsets.only(bottom: heightContainerBottomButton),
              child: Column(
                children: [
                  if (thumbnail.isNotEmpty)
                    NetworkImageWithAspectRatio(
                      imageUrl: thumbnail,
                      placeholder: Container(
                        height: 200,
                        color: Colors.grey.shade200,
                        child: const Center(child: CircularProgressIndicator()),
                      ),
                      errorWidget: Image.asset("assets/images/bg_default_169.png", fit: BoxFit.cover),
                    )
                  else
                    Image.asset("assets/images/bg_default_169.png", fit: BoxFit.cover),
                  Transform.translate(
                    offset: const Offset(0, -32),
                    child: Container(
                      margin: const EdgeInsets.symmetric(horizontal: 16),
                      padding: EdgeInsets.all(16),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        border: Border.all(color: BaseColor.second200),
                        borderRadius: BorderRadius.circular(12),
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.stretch,
                        children: [
                          Text(publishDate, style: const TextStyle(color: Colors.grey, fontSize: 14)),
                          const SizedBox(height: 8),
                          Text(title, style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
                          const SizedBox(height: 8),
                          _buildItems(items),
                          const SizedBox(height: 8),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
            if (showShareButton)
              Positioned(
                top: MediaQuery.of(context).padding.top + 8,
                right: 12,
                child: SizedBox(
                  width: 32,
                  height: 32,
                  child: Material(
                    color: Colors.white,
                    shape: const CircleBorder(),
                    child: IconButton(
                      onPressed: () {
                        final content = pageDetail.shareContent ?? "";
                        SharePlus.instance.share(
                          ShareParams(text: content, title: "Chia sẻ từ MyPoint"),
                        );
                        _viewModel.submitShareContent();
                      },
                      icon: const Icon(Icons.share, size: 16),
                    ),
                  ),
                ),
              ),
            Positioned(top: MediaQuery.of(context).padding.top + 8, left: 8, child: CustomBackButton()),
            if (buttonOn == "1") _bottomButton(pageDetail),
          ],
        );
      }),
    );
  }

  Widget _bottomButton(CampaignDetailModel? pageDetail) {
    final buttonColor = pageDetail?.buttonColor ?? "#d9d9d9";
    final buttonName = pageDetail?.buttonName ?? "";
    final buttonTextColor = pageDetail?.buttonTextColor ?? "#FFFFFF";
    return Positioned(
      left: 16,
      right: 16,
      bottom: 0,
      child: Container(
        color: BaseColor.second200,
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).padding.bottom + 16 + 48,
        child: Center(
          child: Column(
            children: [
              SizedBox(height: 12),
              ElevatedButton(
                onPressed: () {
                  print(pageDetail?.directionalScreen);
                  print(pageDetail?.buttonClickActionType);
                  print(pageDetail?.buttonClickActionParam);
                  pageDetail?.directionalScreen?.begin();
                },
                style: ElevatedButton.styleFrom(
                  backgroundColor: parseHexColor(buttonColor),
                  minimumSize: const Size.fromHeight(48),
                ),
                child: Text(
                  buttonName,
                  style: TextStyle(color: parseHexColor(buttonTextColor), fontWeight: FontWeight.bold),
                ),
              ),
              SizedBox(height: MediaQuery.of(context).padding.bottom),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildItems(List<CampaignDetailItemModel> items) {
    List<Widget> widgets = [];
    for (var item in items) {
      final mediaType = (item.mediaType ?? "").toLowerCase();
      if (mediaType == MediaTypeItemCampaign.image.key || mediaType == MediaTypeItemCampaign.imageLink.key) {
        if (item.contentText != null && item.contentText!.isNotEmpty) {
          widgets.add(
            Padding(
              padding: const EdgeInsets.only(bottom: 16),
              child: NetworkImageWithAspectRatio(
                imageUrl: item.contentText!,
                placeholder: Container(
                  height: 200,
                  color: Colors.grey.shade200,
                  child: const Center(child: CircularProgressIndicator()),
                ),
                errorWidget: Image.asset("assets/bg_header_campain_default.png", fit: BoxFit.cover),
              ),
            ),
          );
        }
      } else if (mediaType == MediaTypeItemCampaign.text.key) {
        if (item.contentText != null && item.contentText!.isNotEmpty) {
          widgets.add(
            Padding(
              padding: const EdgeInsets.only(bottom: 16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  if ((item.contentCaption ?? "").isNotEmpty)
                    Text(item.contentCaption!, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
                  const SizedBox(height: 4),
                  HtmlWidget(item.contentText!),
                ],
              ),
            ),
          );
        }
      } else if (mediaType == MediaTypeItemCampaign.pageLink.key) {
        if (item.pages?.isNotEmpty == true) {
          for (var item in item.pages!) {
            widgets.add(
              CampaignItemPageWidget(
                itemPageCampaign: item,
                onTap: () async {
                  Get.offNamed(campaignDetailScreen, arguments: {"id": item.pageId}, preventDuplicates: false);
                },
              ),
            );
          }
        }
      }
    }
    return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: widgets);
  }
}
