import 'package:flutter/material.dart';
import 'package:flutter_widget_from_html/flutter_widget_from_html.dart';
import 'package:get/get.dart';
import '../../base/base_screen.dart';
import '../../base/basic_state.dart';
import '../../extensions/string_extension.dart'; // tuỳ dự án
import '../../resouce/base_color.dart';
import '../../widgets/back_button.dart';
import '../../widgets/network_image_with_aspect_ratio.dart'; // widget custom
import 'campaign_detail_viewmodel.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 {
  final DetailPageRuleType? type;
  final String? pageId;

  const CampaignDetailScreen({super.key, this.type, this.pageId});

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

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

  @override
  void initState() {
    super.initState();
    ever(_viewModel.errorMessage, (value) {
      if (value != null && value.toString().isNotEmpty) {
        WidgetsBinding.instance.addPostFrameCallback((_) {
          showAlertError(value);
        });
      }
    });
    _viewModel.fetchData(widget.type, widget.pageId);
  }

  @override
  Widget createBody() {
    return Scaffold(
      backgroundColor: BaseColor.second200,
      body: Obx(() {
        CampaignDetailModel? pageDetail = _viewModel.campaignDetail.value.data?.pageDetail;
        if (pageDetail == null) {
          return const Center(child: CircularProgressIndicator());
        }
        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;
        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_header_campaign_default.png", fit: BoxFit.cover),
                    )
                  else
                    Image.asset("assets/images/bg_header_campaign_default.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: 16),
                          _buildItems(items),
                          const SizedBox(height: 8),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
            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: () {
                  // Xử lý khi bấm nút
                },
                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?.value ?? ""; //toLowerCase() ?? "";
      if (mediaType == MediaTypeItemCampaign.image.name) {
        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.name) {
        if (item.contentText != null && item.contentText!.isNotEmpty) {
          widgets.add(Padding(padding: const EdgeInsets.only(bottom: 16), child: HtmlWidget(item.contentText!)));
        }
      }
    }
    return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: widgets);
  }
}
