import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter_widget_from_html/flutter_widget_from_html.dart';
import 'package:mypoint_flutter_app/extensions/num_extension.dart';
import 'package:mypoint_flutter_app/extensions/string_extension.dart';
import 'package:mypoint_flutter_app/screen/voucher/detail/store_list_section.dart';
import 'package:mypoint_flutter_app/screen/voucher/models/product_type.dart';
import 'package:mypoint_flutter_app/screen/voucher/voucher_code_card_screen.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../../base/base_screen.dart';
import '../../../base/basic_state.dart';
import '../../../preference/point/point_manager.dart';
import '../../../resources/base_color.dart';
import '../../../shared/router_gage.dart';
import '../../../widgets/alert/data_alert_model.dart';
import '../../../widgets/back_button.dart';
import '../../../widgets/custom_empty_widget.dart';
import '../../../widgets/custom_point_text_tag.dart';
import '../../../widgets/dashed_line.dart';
import '../../../widgets/image_loader.dart';
import '../../../widgets/measure_size.dart';
import '../models/cash_type.dart';
import '../models/my_product_status_type.dart';
import '../models/product_model.dart';
import 'voucher_detail_viewmodel.dart';
import 'package:get/get.dart';

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

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

class _VoucherDetailScreenState extends BaseState<VoucherDetailScreen> with BasicState {
  late final VoucherDetailViewModel _viewModel;
  double _infoHeight = 0;

  @override
  void initState() {
    super.initState();

    int? productId;
    int? customerProductId;

    final args = Get.arguments;
    if (args is int) {
      productId = args;
    } else if (args is String) {
      productId = int.tryParse(args);
    } else if (args is Map) {
      productId = args['productId'];
      customerProductId = args['customerProductId'];
    }
    if (productId == null && customerProductId == null) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        Get.back();
      });
      return;
    }
    _viewModel = Get.put(VoucherDetailViewModel(productId: productId, customerProductId: customerProductId));
    _viewModel.onShowAlertError = (message) {
      if (message.isEmpty) return;
      showAlertError(content: message);
    };
  }

  @override
  Widget createBody() {
    return Scaffold(
      backgroundColor: Colors.grey.shade100,
      body: Obx(() {
        if (_viewModel.isLoading.value) {
          return const Center(child: CircularProgressIndicator());
        }
        final product = _viewModel.product.value;
        if (product == null) {
          return Stack(
            children: [
              const Center(child: EmptyWidget()),
              SafeArea(child: Padding(padding: const EdgeInsets.all(8), child: CustomBackButton())),
            ],
          );
        }
        return Stack(
          children: [
            SingleChildScrollView(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  _buildHeaderWithInfo(product),
                  SizedBox(height: max(_infoHeight - 36, 0)),
                  _buildTextBlock("Chi tiết ưu đãi:", product.content?.detail),
                  _buildTextBlock("Điều kiện áp dụng:", product.content?.termAndCondition),
                  SizedBox(height: 8),
                  StoreListSection(stores: _viewModel.stores, brandLogo: product.brand?.logo ?? ""),
                  _buildSupportBlock(product),
                  Container(color: Colors.grey.shade100, child: SizedBox(height: 64)),
                ],
              ),
            ),
            SafeArea(
              child: Padding(
                padding: const EdgeInsets.all(8),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [CustomBackButton(), _buildFavoriteButton()],
                ),
              ),
            ),
            // SafeArea(child: Padding(padding: const EdgeInsets.all(8), child: CustomBackButton())),
          ],
        );
      }),
      bottomNavigationBar: Obx(() {
        final product = _viewModel.product.value;
        if (product == null) {
          return const SizedBox.shrink();
        }
        return _buildBottomAction(product);
      }),
    );
  }

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

    return Stack(
      clipBehavior: Clip.none,
      children: [
        loadNetworkImage(
          url: product.banner?.url,
          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 (_infoHeight != size.height) {
                setState(() {
                  _infoHeight = size.height;
                });
              }
            },
            child: Transform.translate(
              offset: Offset(0, imageHeight - 36), // ✅ Lấn lên trên ảnh 36px
              child: _buildInfo(product),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildInfo(ProductModel product, {Key? key}) {
    return Container(
      key: key,
      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: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Text(
            product.content?.name ?? '',
            textAlign: TextAlign.center,
            style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
          ),
          const SizedBox(height: 8),
          _buildExpireAndStock(product),
          const SizedBox(height: 16),
          DashedLine(color: Colors.grey.shade400, dashWidth: 3, dashSpacing: 3, height: 1),
          const Divider(height: 16),
          Row(
            children: [
              CircleAvatar(
                radius: 12,
                backgroundColor: Colors.transparent,
                child: ClipOval(
                  child: loadNetworkImage(
                    url: product.brand?.logo ?? "",
                    width: 24,
                    height: 24,
                    fit: BoxFit.cover,
                    placeholderAsset: 'assets/images/ic_logo.png',
                  ),
                ),
              ),
              const SizedBox(width: 8),
              Expanded(child: Text(product.brand?.name ?? '', style: const TextStyle(fontSize: 14))),
              // PriceTagWidget(point: product.amountToBePaid ?? 0),
              CustomPointText(point: product.amountToBePaid ?? 0, type: product.price?.method),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildExpireAndStock(ProductModel product) {
    final bool isOutOfStock = !(product.inStock ?? true);
    final bool hasExpire = product.expire.isNotEmpty;
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        if (hasExpire)
          Text('Hạn dùng: ', style: const TextStyle(color: Colors.grey, fontWeight: FontWeight.bold, fontSize: 12)),
        if (hasExpire)
          Text(
            product.expired ? "Hết hạn" : product.expire,
            style: const TextStyle(color: BaseColor.primary500, fontWeight: FontWeight.bold, fontSize: 12),
          ),
        if (isOutOfStock && !_viewModel.isMyProduct)
          Container(
            margin: const EdgeInsets.only(left: 8),
            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
            decoration: BoxDecoration(color: Colors.grey, borderRadius: BorderRadius.circular(4)),
            child: const Text(
              'Tạm hết',
              style: TextStyle(color: Colors.white, fontSize: 12, fontWeight: FontWeight.bold),
            ),
          ),
      ],
    );
  }

  Widget _buildTextBlock(String title, String? content) {
    if (content == null || content.isEmpty) return const SizedBox();
    return Container(
      padding: const EdgeInsets.all(16),
      margin: const EdgeInsets.only(top: 16, left: 16, right: 16, bottom: 0),
      decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(16)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(title, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
          const SizedBox(height: 8),
          HtmlWidget(content, textStyle: const TextStyle(fontSize: 13, color: Colors.black54)),
        ],
      ),
    );
  }

  Widget _buildSupportBlock(ProductModel product) {
    final brand = product.brand;
    if (brand == null) return const SizedBox.shrink();
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(16)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text('Hỗ trợ:', style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
          const SizedBox(height: 4),
          Text(
            'Nếu bạn gặp bất kỳ vấn đề gì với voucher này, xin vui lòng liên hệ ${brand.name ?? ''}',
            style: const TextStyle(fontSize: 13, color: Colors.black54),
          ),
          const SizedBox(height: 12),
          if ((brand.phone ?? '').isNotEmpty)
            _buildContactRow(
              Icons.phone,
              brand.phone ?? '',
              onTap: () async {
                final Uri phoneUri = Uri.parse('tel:${brand.phone}');
                _launchUri(phoneUri);
              },
            ),
          if ((brand.email ?? '').isNotEmpty)
            _buildContactRow(
              Icons.email_outlined,
              brand.email ?? '',
              onTap: () async {
                final Uri emailUri = Uri.parse('mailto:${brand.email}');
                _launchUri(emailUri);
              },
            ),
          if ((brand.website ?? '').isNotEmpty)
            _buildContactRow(
              Icons.language,
              brand.website ?? '',
              onTap: () {
                final website = brand.website?.trim() ?? "";
                final uri = website.toUri();
                if (uri == null) return;
                _launchUri(uri);
              },
            ),
        ],
      ),
    );
  }

  Future<void> _launchUri(Uri uri) async {
    if (await canLaunchUrl(uri)) {
      print('Launching $uri');
      await launchUrl(uri);
    } else {
      throw 'Could not launch $uri';
    }
  }

  Widget _buildContactRow(IconData icon, String value, {VoidCallback? onTap}) {
    return InkWell(
      onTap: onTap,
      child: Padding(
        padding: const EdgeInsets.only(bottom: 8),
        child: Row(
          children: [
            Icon(icon, size: 18, color: Colors.black54),
            const SizedBox(width: 8),
            Expanded(child: Text(value, style: const TextStyle(fontSize: 13, color: Colors.black))),
            const Icon(Icons.chevron_right, color: Colors.black54),
          ],
        ),
      ),
    );
  }

  Widget _buildBottomAction(ProductModel product) {
    final bool isOutOfStock = !(product.inStock ?? true);
    if (product.isMyProduct && product.customerInfoModel?.status != MyProductStatusType.waiting) {
      return const SizedBox.shrink();
    }
    if (product.expired) {
      return const SizedBox.shrink();
    }
    if (product.isMyProduct) {
      return _buildUseButton();
    } else if (isOutOfStock) {
      return const SizedBox.shrink();
    } else if (product.price?.method == CashType.point) {
      return _buildExchangeButton();
    } else {
      return _buildBuyButtonWithCounter();
    }
  }

  Widget _buildBottomActionContainer({required Widget child}) {
    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: child),
    );
  }

  Widget _buildUseButton() {
    return _buildBottomActionContainer(
      child: SizedBox(
        width: double.infinity,
        height: 48,
        child: ElevatedButton(
          onPressed: () {
            if (_viewModel.product.value == null) return;
            Get.to(() => VoucherCodeCardScreen(product: _viewModel.product.value!));
          },
          style: ElevatedButton.styleFrom(
            backgroundColor: Colors.green,
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
          ),
          child: const Text(
            'Sử Dụng',
            style: TextStyle(fontSize: 16, color: Colors.white, fontWeight: FontWeight.bold),
          ),
        ),
      ),
    );
  }

  Widget _buildExchangeButton() {
    return _buildBottomActionContainer(
      child: SizedBox(
        width: double.infinity,
        height: 48,
        child: ElevatedButton(
          onPressed: () {
            _handleContinueButtonAction();
          },
          style: ElevatedButton.styleFrom(
            backgroundColor: BaseColor.primary500,
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
          ),
          child: const Text(
            'Đổi Ưu Đãi',
            style: TextStyle(fontSize: 16, color: Colors.white, fontWeight: FontWeight.bold),
          ),
        ),
      ),
    );
  }

  Widget _buildBuyButtonWithCounter() {
    return _buildBottomActionContainer(
      child: Row(
        children: [
          if (_viewModel.product.value?.productType == ProductType.voucher)
            Row(
              children: [
                Container(
                  decoration: BoxDecoration(
                    color: Colors.white,
                    border: Border.all(color: Colors.grey.shade300),
                    borderRadius: BorderRadius.circular(50),
                  ),
                  child: IconButton(
                    icon: const Icon(Icons.remove, color: Colors.black),
                    onPressed: () {
                      if (_viewModel.quantity.value > 1) {
                        _viewModel.quantity.value--;
                      }
                    },
                  ),
                ),
                const SizedBox(width: 12),
                Obx(() => Text('${_viewModel.quantity.value}', style: const TextStyle(fontSize: 16))),
                const SizedBox(width: 12),
                Container(
                  decoration: BoxDecoration(
                    color: BaseColor.primary500,
                    border: Border.all(color: Colors.grey.shade300),
                    borderRadius: BorderRadius.circular(50),
                  ),
                  child: IconButton(
                    icon: const Icon(Icons.add, color: Colors.white),
                    onPressed: () {
                      _viewModel.quantity.value++;
                    },
                  ),
                ),
                const SizedBox(width: 24),
              ],
            ),
          Expanded(
            child: SizedBox(
              height: 48,
              child: ElevatedButton(
                onPressed: () {
                  _handleContinueButtonAction();
                },
                style: ElevatedButton.styleFrom(
                  backgroundColor: BaseColor.primary500,
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
                ),
                child: const Text(
                  'Mua ngay',
                  style: TextStyle(fontSize: 16, color: Colors.white, fontWeight: FontWeight.bold),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  void _handleContinueButtonAction() {
    final product = _viewModel.product.value;
    if (product?.requireFormRegis == true) {
      Get.toNamed(registerFormInputScreen, arguments: {"product": product});
      return;
    }
    _viewModel.verifyOrderProduct(() {
      if (product?.price?.method == CashType.point) {
        _handleRedeemProduct();
      } else {
        Get.toNamed(transactionDetailScreen, arguments: {"product": product, "quantity": _viewModel.quantity.value});
      }
    });
  }

  _handleRedeemProduct() {
    final amountToBePaid = _viewModel.product.value?.amountToBePaid ?? 0;
    if (UserPointManager().point < amountToBePaid) {
      showAlertError(content: "Bạn không đủ điểm để đổi ưu đãi này");
      return;
    }
    final dataAlert = DataAlertModel(
      title: "Xác nhận",
      description:
          "Bạn có muốn sử dụng <b style=\"color:#E71D28\"> ${amountToBePaid.money(CurrencyUnit.point)}</b> MyPoint  để đổi Ưu Đãi này không?",
      localHeaderImage: "assets/images/ic_pipi_02.png",
      buttons: [
        AlertButton(
          text: "Đồng ý",
          onPressed: () {
            Get.back();
            _viewModel.redeemProduct();
          },
          bgColor: BaseColor.primary500,
          textColor: Colors.white,
        ),
        AlertButton(text: "Huỷ", onPressed: () => Get.back(), bgColor: Colors.white, textColor: BaseColor.second500),
      ],
    );
    showAlert(data: dataAlert);
  }

  Widget _buildFavoriteButton() {
    return Obx(() {
      final isFavorite = _viewModel.liked.value;
      return Align(
        alignment: Alignment.topRight,
        child: Padding(
          padding: const EdgeInsets.only(top: 8, right: 8),
          child: GestureDetector(
            onTap: () {
              _viewModel.toggleFavorite();
            },
            child: Container(
              width: 40,
              height: 40,
              decoration: BoxDecoration(color: Colors.grey.withOpacity(0.6), shape: BoxShape.circle),
              child: Icon(Icons.favorite, color: isFavorite ? BaseColor.primary500 : Colors.white, size: 24),
            ),
          ),
        ),
      );
    });
  }
}
