import 'dart:math';
import 'package:flutter/material.dart';
import 'package:mypoint_flutter_app/extensions/num_extension.dart';
import '../../../base/base_screen.dart';
import '../../../base/basic_state.dart';
import '../../resources/base_color.dart';
import '../../widgets/back_button.dart';
import '../../widgets/image_loader.dart';
import '../../widgets/measure_size.dart';
import 'affiliate_brand_detail_tip_box.dart';
import 'affiliate_brand_detail_viewmodel.dart';
import 'package:get/get.dart';

import 'affiliate_brand_detail_tag_list.dart';

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

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

class _AffiliateBrandDetailScreenState extends BaseState<AffiliateBrandDetailScreen> with BasicState {
  late final AffiliateBrandDetailViewModel _viewModel;
  double _infoHeight = 0;

  @override
  void initState() {
    super.initState();
    String? brandId;
    final args = Get.arguments;
    if (args is Map) {
      brandId = args['brandId'];
    }
    if ((brandId ?? '').isEmpty) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        Get.back();
      });
      return;
    }
    _viewModel = Get.put(AffiliateBrandDetailViewModel(brandId ?? ''));
    _viewModel.onShowAlertError = (message) {
      if (message.isNotEmpty) {
        showAlertError(content: message);
      }
    };
  }

  @override
  Widget createBody() {
    return Scaffold(
      backgroundColor: Colors.grey.shade100,
      body: Obx(() {
        double heightStepTutorial = 100;
        var categoriesTag = _viewModel.brandDetailData.value?.categories ?? [];
        var shoulds = _viewModel.brandDetailData.value?.contentShould ?? [];
        var shouldnts = _viewModel.brandDetailData.value?.contentShouldnt ?? [];
        var notes = _viewModel.brandDetailData.value?.contentNote ?? [];
        var others = _viewModel.brandDetailData.value?.contentOther ?? [];

        return Stack(
          children: [
            SingleChildScrollView(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  _buildHeaderWithInfo(),
                  SizedBox(height: max(_infoHeight - 54, 0)),
                  _buildCardGuide(),
                  Container(
                    color: Colors.white,
                    margin: EdgeInsets.only(top: 16, bottom: 16),
                    padding: EdgeInsets.only(top: 16, bottom: 16),
                    child: SizedBox(
                      height: heightStepTutorial,
                      child: ListView(
                        scrollDirection: Axis.horizontal,
                        children: [
                          const SizedBox(width: 12),
                          _buildStepCard(heightStepTutorial, "assets/images/banner_tutorial_refund_point_step1.png"),
                          const SizedBox(width: 12),
                          _buildStepCard(heightStepTutorial, "assets/images/banner_tutorial_refund_point_step2.png"),
                          const SizedBox(width: 12),
                          _buildStepCard(heightStepTutorial, "assets/images/banner_tutorial_refund_point_step3.png"),
                          const SizedBox(width: 12),
                          _buildStepCard(heightStepTutorial, "assets/images/banner_tutorial_refund_point_step4.png"),
                          const SizedBox(width: 12),
                        ],
                      ),
                    ),
                  ),
                  if (categoriesTag.isNotEmpty) AffiliateTagListScrollable(items: categoriesTag),
                  if (shoulds.isNotEmpty) AffiliateBrandDetailTipBox(type: AffiliateTipBoxType.should, tips: shoulds),
                  if (shouldnts.isNotEmpty)
                    AffiliateBrandDetailTipBox(type: AffiliateTipBoxType.shouldnt, tips: shouldnts),
                  if (notes.isNotEmpty) AffiliateBrandDetailTipBox(type: AffiliateTipBoxType.note, tips: notes),
                  if (others.isNotEmpty) AffiliateBrandDetailTipBox(type: AffiliateTipBoxType.other, tips: others),
                ],
              ),
            ),
            SafeArea(child: Padding(padding: const EdgeInsets.only(left: 12), child: CustomBackButton())),
          ],
        );
      }),
      bottomNavigationBar: _buildButton(),
    );
  }

  Widget _buildButton() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
      decoration: const BoxDecoration(
        color: Colors.white,
        boxShadow: [BoxShadow(color: Colors.black54, blurRadius: 8, offset: Offset(0, 4))],
      ),
      child: SafeArea(
        top: false,
        child: ElevatedButton(
          onPressed: () {
            _viewModel.brandDetailData.value?.directionalScreen?.begin();
          },
          style: ElevatedButton.styleFrom(
            backgroundColor: BaseColor.primary500,
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
            minimumSize: const Size.fromHeight(48),
          ),
          child: const Text(
            "Mua ngay",
            style: TextStyle(fontSize: 16, color: Colors.white, fontWeight: FontWeight.bold),
          ),
        ),
      ),
    );
  }

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

    return Stack(
      clipBehavior: Clip.none,
      children: [
        loadNetworkImage(
          url: _viewModel.brandDetailData.value?.background,
          fit: BoxFit.cover,
          height: imageHeight,
          width: double.infinity,
          placeholderAsset: 'assets/images/bg_header_detail_brand.png',
        ),
        Positioned(
          left: 0,
          right: 0,
          child: MeasureSize(
            onChange: (size) {
              if (_infoHeight != size.height) {
                setState(() {
                  _infoHeight = size.height;
                });
              }
            },
            child: Transform.translate(offset: Offset(0, imageHeight - 60), child: _buildCardInfo()),
          ),
        ),
      ],
    );
  }

  Widget _buildCardGuide() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset('assets/images/ic_time_record.png', width: 36, height: 36),
            const SizedBox(width: 4),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text('Ghi nhận sau', style: TextStyle(color: Colors.black54, fontSize: 12)),
                Text(
                  _viewModel.brandDetailData.value?.timeConfirm ?? "",
                  style: TextStyle(color: Colors.black87, fontSize: 12, fontWeight: FontWeight.w700),
                ),
              ],
            ),
          ],
        ),
        Padding(
          padding: const EdgeInsets.only(left: 18, right: 18),
          child: Container(
            width: 1,
            height: 40,
            color: Colors.grey.shade300,
            margin: const EdgeInsets.symmetric(horizontal: 12),
          ),
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset('assets/images/ic_time_refund.png', width: 36, height: 36),
            const SizedBox(width: 4),
            Column(
              children: [
                const Text('Hoàn điểm sau', style: TextStyle(color: Colors.black54, fontSize: 12)),
                Text(
                  _viewModel.brandDetailData.value?.timeCashback ?? "",
                  style: TextStyle(color: Colors.black87, fontSize: 12, fontWeight: FontWeight.w700),
                ),
              ],
            ),
          ],
        ),
      ],
    );
  }

  Widget _buildCardInfo() {
    final detail = _viewModel.brandDetailData.value;
    if (detail == null) return SizedBox();
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
      padding: const EdgeInsets.all(10),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [BoxShadow(color: Colors.black12, blurRadius: 6, offset: Offset(0, 3))],
      ),
      child: Row(
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(8),
            child: loadNetworkImage(
              url: detail.logo,
              width: 60,
              height: 60,
              placeholderAsset: "assets/images/ic_logo.png",
            ),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(detail.brandName ?? '', style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
                const SizedBox(height: 4),
                RichText(
                  text: TextSpan(
                    text: 'Hoàn đến ',
                    style: const TextStyle(color: Colors.black, fontSize: 13),
                    children: [
                      TextSpan(
                        text: detail.showCommision ?? '',
                        style: const TextStyle(color: Colors.deepOrangeAccent, fontWeight: FontWeight.bold),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          const Icon(Icons.check_circle, color: Colors.green, size: 16),
          const SizedBox(width: 2),
          Text(
            '${detail?.quantitySold?.money(CurrencyUnit.noneSpace) ?? '1'} đơn hàng',
            style: TextStyle(color: Colors.green, fontSize: 13),
          ),
        ],
      ),
    );
  }

  Widget _buildStepCard(double height, String imagePath) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(8),
      child: Image.asset(imagePath, fit: BoxFit.cover, width: height * 4611 / 2739, height: height),
    );
  }
}
