import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../base/base_screen.dart';
import '../../../base/basic_state.dart';
import '../../../shared/router_gage.dart';
import '../../../widgets/custom_empty_widget.dart';
import '../../../widgets/custom_navigation_bar.dart';
import '../../../widgets/image_loader.dart';
import '../../mobile_card/models/usable_voucher_model.dart';
import '../../mobile_card/usable_mobile_card_popup.dart';
import 'my_mobile_card_list_viewmodel.dart';
import 'package:dotted_border/dotted_border.dart';

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

  @override
  State<MyMobileCardListScreen> createState() => _MyMobileCardListScreenState();
}

class _MyMobileCardListScreenState extends BaseState<MyMobileCardListScreen> with BasicState {
  late final MyMobileCardListViewModel _viewModel = Get.put(MyMobileCardListViewModel());

  @override
  initState() {
    super.initState();
    _viewModel.onShowAlertError = (message) {
      if (message.isEmpty) return;
      showAlertError(content: message);
    };

    _viewModel.onRedeemProductMobileSuccess = (data) {
      showVoucherPopup(context, data);
    };
  }

  @override
  Widget createBody() {
    final screenWidth = MediaQuery.of(context).size.width;
    return Scaffold(
      appBar: CustomNavigationBar(title: 'Thẻ nạp của tôi',),
      body: Obx(
        () => Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [_buildTab('Đang có', 0), _buildTab('Đã sử dụng', 1)],
              ),
            ),
            const Divider(height: 1),
            if (_viewModel.myCardModels.isEmpty)
              Expanded(child: EmptyWidget(size: Size(screenWidth / 2, screenWidth / 2)))
            else
              Expanded(
                child: RefreshIndicator(
                  onRefresh: () async {
                    _viewModel.freshData(isRefresh: true);
                  },
                  child: ListView.builder(
                    padding: const EdgeInsets.all(12),
                    itemCount: _viewModel.myCardModels.length,
                    itemBuilder: (_, index) {
                      if (index >= _viewModel.myCardModels.length) {
                        _viewModel.freshData(isRefresh: false);
                        return const Center(
                          child: Padding(padding: EdgeInsets.all(16), child: CircularProgressIndicator()),
                        );
                      }
                      final product = _viewModel.myCardModels[index];
                      return _buildVoucherItem(product);
                    },
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }

  Widget _buildTab(String title, int index) {
    return GestureDetector(
      onTap: () => _viewModel.selectTab(index),
      child: Obx(
        () => Column(
          children: [
            Text(
              title,
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w600,
                color: _viewModel.selectedTabIndex.value == index ? Colors.red : Colors.black54,
              ),
            ),
            const SizedBox(height: 4),
            if (_viewModel.selectedTabIndex.value == index) Container(height: 2, width: 60, color: Colors.red),
          ],
        ),
      ),
    );
  }

  Widget _buildVoucherItem(UsableVoucherModel product) {
    return GestureDetector(
      onTap: () {
        Get.toNamed(myMobileCardDetailScreen, arguments: {"itemId": product.voucherItemID ?? ""});
        // _viewModel.getMobileCardCode(product.voucherItemID ?? "");
        // Get.toNamed(voucherDetailScreen, arguments: {"customerProductId": product.id});
      },
      child: Container(
        margin: const EdgeInsets.symmetric(vertical: 8),
        padding: const EdgeInsets.all(0),
        child: DottedBorder(
          options: RoundedRectDottedBorderOptions(
            color: Colors.redAccent.withOpacity(0.3),
            radius: const Radius.circular(12),
            dashPattern: const [3, 3],
            strokeWidth: 1,
          ),
          child: Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(10),
              color: Colors.redAccent.withOpacity(0.03),
            ),
            padding: const EdgeInsets.all(12),
            child: Row(
              children: [
                ClipRRect(
                  borderRadius: BorderRadius.circular(8),
                  child: loadNetworkImage(
                    url: product.brand?.logo ?? '',
                    width: 64,
                    height: 64,
                    fit: BoxFit.cover,
                    placeholderAsset: "assets/images/bg_default_11.png",
                  ),
                ),
                const SizedBox(width: 16),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      if ((product.brand?.brandName ?? '').isNotEmpty)
                        Text(
                          product.brand?.brandName ?? '',
                          style: const TextStyle(fontWeight: FontWeight.bold, color: Colors.black54, fontSize: 12),
                        ),
                      const SizedBox(height: 6),
                      Text(product.name ?? '', style: const TextStyle(fontSize: 15, fontWeight: FontWeight.w500)),
                      const SizedBox(height: 6),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
