import 'package:auto_size_text/auto_size_text.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/widgets/custom_toast_message.dart';
import 'package:mypoint_flutter_app/widgets/image_loader.dart';
import '../../../resources/base_color.dart';
import '../../../widgets/bottom_sheet_helper.dart';
import '../../../widgets/custom_navigation_bar.dart';
import 'card_recharge_sheet.dart';
import 'my_mobile_card_detail_viewmodel.dart';

class MyMobileCardDetailScreen extends StatefulWidget {
  const MyMobileCardDetailScreen({super.key});

  @override
  State<MyMobileCardDetailScreen> createState() => _MyMobileCardDetailScreenState();
}

class _MyMobileCardDetailScreenState extends State<MyMobileCardDetailScreen> {
  late final MyMobileCardDetailViewModel _viewModel;

  @override
  initState() {
    super.initState();
    String? itemId;

    final args = Get.arguments;
    if (args is String) {
      itemId = args;
    } else if (args is Map) {
      itemId = args['itemId'];
    }
    if (itemId == null) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        Get.back();
      });
      return;
    }
    _viewModel = Get.put(MyMobileCardDetailViewModel(itemId: itemId));
    _viewModel.getMobileCardDetail();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF3F5FA),
      appBar: CustomNavigationBar(title: 'Chi tiết thẻ nạp'),
      body: SafeArea(
        child: LayoutBuilder(
          builder: (ctx, cons) {
            return SingleChildScrollView(
              padding: const EdgeInsets.fromLTRB(16, 16, 16, 24),
              child: Obx(
                () => ConstrainedBox(
                  constraints: BoxConstraints(minHeight: cons.maxHeight - 24),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      _MobileDetailCard(vm: _viewModel),
                      const SizedBox(height: 36),
                      SizedBox(
                        height: 52,
                        child: ElevatedButton(
                          onPressed: _viewModel.isUsed.value ? null : _onRechargeCard,
                          style: ElevatedButton.styleFrom(
                            backgroundColor: _viewModel.isUsed.value ? BaseColor.second500 : BaseColor.primary500,
                            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(26)),
                            elevation: 0,
                          ),
                          child: Text(
                              'Nạp ngay',
                              style: TextStyle(
                                  fontSize: 16,
                                  fontWeight: FontWeight.w600,
                                  color: _viewModel.isUsed.value ? BaseColor.primary500 : Colors.white,
                              )),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            );
          },
        ),
      ),
    );
  }

  void _onRechargeCard() {
    BottomSheetHelper.showBottomSheetPopup(
      child: RechargeSheet(
        code: _viewModel.code,
      ),
    );
  }
}

class _MobileDetailCard extends StatelessWidget {
  final MyMobileCardDetailViewModel vm;
  const _MobileDetailCard({required this.vm});

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: const [BoxShadow(color: Color(0x22000000), blurRadius: 12, offset: Offset(0, 4))],
      ),
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Container(
                color: Colors.white,
                child: loadNetworkImage(url: vm.dataCard.value?.brand?.logo, width: 48, height: 48),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      vm.valueText.isEmpty ? (vm.dataCard.value?.voucherValue ?? '') : vm.valueText,
                      style: TextStyle(fontSize: 20, fontWeight: FontWeight.w600),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                    const SizedBox(height: 2),
                    Text(vm.brandName),
                  ],
                ),
              ),
              const SizedBox(width: 8),
              // status
              GestureDetector(
                onTap: () {
                  vm.onChangeCardStatus();
                },
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(vm.isUsed.value ? 'Đã sử dụng' : 'Đánh dấu đã sử dụng'),
                    const SizedBox(width: 6),
                    Icon(Icons.fiber_manual_record, size: 18, color: vm.isUsed.value ? const Color(0xFF24C26A) : Colors.grey),
                  ],
                ),
              ),
            ],
          ),
          const SizedBox(height: 24),
          Text('Mã thẻ'),
          const SizedBox(height: 8),
          _buildCodeRow(),
          const SizedBox(height: 16),
          _buildSerialRow(),
        ],
      ),
    );
  }

  Widget _buildSerialRow() {
    if (vm.serial.isEmpty) return const SizedBox.shrink();
    return Row(
      children: [
        Text('Số seri: '),
        Expanded(
          child: AutoSizeText(
            vm.serial,
            style: TextStyle(color: Colors.black),
            maxLines: 1,
            minFontSize: 10,
          ),
        ),
        const SizedBox(width: 6),
        InkWell(
          onTap: () async {
            if (vm.serial.isEmpty) return;
            await Clipboard.setData(ClipboardData(text: vm.serial));
            showToastMessage('Đã sao chép số seri');
          },
          borderRadius: BorderRadius.circular(6),
          child: const Padding(
            padding: EdgeInsets.all(2.0),
            child: Icon(Icons.copy, size: 16, color: Colors.black45),
          ),
        ),
      ],
    );
  }

  Widget _buildCodeRow() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
      decoration: BoxDecoration(color: const Color(0xFFF4F6F8), borderRadius: BorderRadius.circular(12)),
      child: Row(
        children: [
          Expanded(
            child: SelectableText(
              vm.code.isEmpty ? '—' : vm.code,
              style: TextStyle(
                fontSize: 16,
                color: Colors.black,
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
          const SizedBox(width: 4),
          IconButton(
            onPressed: () async {
              if (vm.code.isEmpty) return;
              await Clipboard.setData(ClipboardData(text: vm.code));
              showToastMessage('Đã sao chép mã thẻ');
            },
            icon: const Icon(Icons.copy, size: 20, color: Colors.black45),
            padding: EdgeInsets.zero,
            constraints: const BoxConstraints(minWidth: 36, minHeight: 36),
            splashRadius: 18,
          ),
        ],
      ),
    );
  }
}