import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/shared/widgets/base_view/base_screen.dart';
import 'package:mypoint_flutter_app/shared/widgets/base_view/basic_state.dart';
import 'package:mypoint_flutter_app/core/utils/extensions/num_extension.dart';
import 'package:mypoint_flutter_app/features/flash_sale/flash_sale_viewmodel.dart';
import 'package:mypoint_flutter_app/features/flash_sale/models/flash_sale_category_model.dart';
import 'package:mypoint_flutter_app/features/voucher/models/product_model.dart';
import 'package:mypoint_flutter_app/shared/widgets/custom_empty_widget.dart';
import 'package:mypoint_flutter_app/shared/widgets/image_loader.dart';
import '../../shared/router_gage.dart';
import '../../shared/widgets/custom_navigation_bar.dart';

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

  @override
  State<StatefulWidget> createState() => _FlashSaleScreenState();
}

class _FlashSaleScreenState extends BaseState<FlashSaleScreen> with BasicState {
  late final FlashSaleViewModel _viewModel;

  @override
  void initState() {
    super.initState();
    final args = Get.arguments;
    final dynamic rawId = args is Map ? (args['groupId'] ?? args['id']) : args;
    final String groupId = (rawId == null || rawId.toString().isEmpty) ? '294' : rawId.toString();
    _viewModel = Get.put(FlashSaleViewModel(groupId: groupId));
    _viewModel.onShowAlertError ??= (message) => showAlertError(content: message);
  }

  @override
  Widget createBody() {
    return Scaffold(
      backgroundColor: Colors.grey[200],
      appBar: const CustomNavigationBar(title: 'Flash Sale'),
      body: NotificationListener<ScrollNotification>(
        onNotification: (notification) {
          if (notification is ScrollUpdateNotification &&
              notification.metrics.axis == Axis.vertical &&
              notification.metrics.pixels >= notification.metrics.maxScrollExtent - 200) {
            _viewModel.loadMore();
          }
          return false;
        },
        child: RefreshIndicator(
          onRefresh: _viewModel.refresh,
          child: CustomScrollView(
            physics: const AlwaysScrollableScrollPhysics(),
            slivers: [
              SliverToBoxAdapter(child: Obx(() => _buildCategorySection())),
              SliverToBoxAdapter(child: Obx(() => _buildCountdownSection())),
              Obx(() => _buildProductSliver()),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildCategorySection() {
    final categories = _viewModel.categories;
    if (categories.isEmpty) return const SizedBox.shrink();
    final selectedId = _viewModel.selectedCategoryId.value ?? FlashSaleViewModel.allCategory.id;
    return Container(
      color: Colors.white,
      height: 72,
      child: ListView.separated(
        scrollDirection: Axis.horizontal,
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        itemCount: categories.length,
        separatorBuilder: (_, _) => const SizedBox(width: 8),
        itemBuilder: (_, index) {
          final category = categories[index];
          final bool isSelected = selectedId == category.id;
          return _buildCategoryChip(category, isSelected);
        },
      ),
    );
  }

  Widget _buildCategoryChip(FlashSaleCategoryModel category, bool isSelected) {
    final Color accent = isSelected ? const Color(0xFFE53935) : const Color(0xFFE0E0E0);
    final Color textColor = isSelected ? const Color(0xFFE53935) : Colors.black87;
    return GestureDetector(
      onTap: () => _viewModel.onCategorySelected(category),
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(8),
          border: Border.all(color: accent, width: 1),
        ),
        child: Center(
          child: Text(category.name ?? '', style: TextStyle(color: textColor, fontWeight: FontWeight.w600)),
        ),
      ),
    );
  }

  Widget _buildCountdownSection() {
    final sale = _viewModel.products.firstOrNull?.previewFlashSale;
    if (sale == null) return const SizedBox.shrink();
    final duration = _viewModel.remaining.value;
    final bool isCounting = duration.inSeconds > 0;
    final label = (sale.desTime ?? 'Kết thúc trong').toUpperCase();
    return Container(
      padding: const EdgeInsets.only(left: 16, right: 16, top: 12, bottom: 0),
      child: Row(
        children: [
          const Spacer(),
          Text(label, style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w700, color: Colors.black54)),
          const SizedBox(width: 12),
          _buildTimeChip(_formatTwoDigits(duration.inHours)),
          const SizedBox(width: 4),
          const Text(':', style: TextStyle(fontWeight: FontWeight.bold)),
          const SizedBox(width: 4),
          _buildTimeChip(_formatTwoDigits(duration.inMinutes.remainder(60))),
          const SizedBox(width: 4),
          const Text(':', style: TextStyle(fontWeight: FontWeight.bold)),
          const SizedBox(width: 4),
          _buildTimeChip(_formatTwoDigits(duration.inSeconds.remainder(60))),
          if (!isCounting)
            const Text(
              'Đã kết thúc',
              style: TextStyle(fontSize: 12, color: Colors.redAccent, fontWeight: FontWeight.w600),
            ),
        ],
      ),
    );
  }

  Widget _buildTimeChip(String value) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 4),
      decoration: BoxDecoration(color: const Color(0xFF212121), borderRadius: BorderRadius.circular(6)),
      child: Text(value, style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold)),
    );
  }

  Widget _buildProductSliver() {
    final products = _viewModel.products;
    if (products.isEmpty) {
      return SliverFillRemaining(
        hasScrollBody: false,
        child: EmptyWidget(isLoading: _viewModel.isLoading.value),
      );
    }
    final double screenWidth = MediaQuery.of(context).size.width;
    final double itemWidth = (screenWidth - 36) / 2;
    final bool showProgress = products.firstOrNull?.isShowProsessSoldItem ?? false;
    // 16 space top-bottom content
    // 24 height price
    // 48 height name
    final double itemHeight = itemWidth * 9 / 16 + 16 + 24 + 48 + (showProgress ? 24 : 0);
    return SliverPadding(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
      sliver: SliverGrid(
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          mainAxisSpacing: 12,
          crossAxisSpacing: 12,
          childAspectRatio: itemWidth / itemHeight,
        ),
        delegate: SliverChildBuilderDelegate(
          (context, index) => _buildProductCard(products[index]),
          childCount: products.length,
        ),
      ),
    );
  }

  Widget _buildProductCard(ProductModel product) {
    final percent = product.percentDiscount;
    final bool showProgress = product.isShowProsessSoldItem;
    return GestureDetector(
      onTap: () => Get.toNamed(voucherDetailScreen, arguments: {"productId": product.id}),
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(16),
          boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.04), blurRadius: 8, offset: const Offset(0, 4))],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            ClipRRect(
              borderRadius: const BorderRadius.vertical(top: Radius.circular(16)),
              child: AspectRatio(
                aspectRatio: 16 / 9,
                child: Stack(
                  fit: StackFit.expand,
                  children: [
                    loadNetworkImage(
                      url: product.banner?.url ?? '',
                      fit: BoxFit.cover,
                      placeholderAsset: 'assets/images/bg_default_169.png',
                    ),
                    if (percent != null)
                      Positioned(
                        right: 8,
                        bottom: 8,
                        child: Container(
                          padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                          decoration: BoxDecoration(
                            color: const Color(0xFFE53935),
                            borderRadius: BorderRadius.circular(20),
                          ),
                          child: Text(
                            '-$percent%',
                            style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 12),
                          ),
                        ),
                      ),
                  ],
                ),
              ),
            ),
            Expanded(
              child: Padding(
                padding: const EdgeInsets.all(8),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Image.asset('assets/images/ic_hot_flash_sale.png', width: 20, height: 20),
                        const SizedBox(width: 4),
                        Text(
                          product.amountToBePaid?.money(CurrencyUnit.vnd) ?? '',
                          style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w700, color: Colors.black87),
                        ),
                        if ((product.price?.value ?? 0) > 0)
                          Padding(
                            padding: const EdgeInsets.only(left: 4),
                            child: Text(
                              '${product.price?.value?.money(CurrencyUnit.noneSpace)}đ',
                              style: const TextStyle(
                                fontSize: 14,
                                color: Colors.grey,
                                decoration: TextDecoration.lineThrough,
                              ),
                            ),
                          ),
                      ],
                    ),
                    const SizedBox(height: 6),
                    Text(
                      product.name ?? '',
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                      style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w600),
                    ),
                    if (showProgress) ...[
                      const SizedBox(height: 6),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          SizedBox(
                            width: 100,
                            child: ClipRRect(
                              borderRadius: BorderRadius.circular(4),
                              child: LinearProgressIndicator(
                                value: product.progress,
                                minHeight: 6,
                                backgroundColor: Colors.grey.shade300,
                                valueColor: AlwaysStoppedAnimation<Color>(product.inStock ? Colors.orange : Colors.red),
                              ),
                            ),
                          ),
                          const SizedBox(width: 2),
                          Text(
                            product.inStock ? 'Đã bán ${product.previewFlashSale?.fsQuantitySold ?? 0}' : 'Đã bán hết',
                            style: TextStyle(fontSize: 12, color: product.inStock ? Colors.black : Colors.grey),
                          ),
                        ],
                      ),
                    ],
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  String _formatTwoDigits(int value) => value.toString().padLeft(2, '0');
}
