import 'package:barcode_widget/barcode_widget.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/extensions/num_extension.dart';
import 'package:mypoint_flutter_app/extensions/string_extension.dart';
import 'package:mypoint_flutter_app/preference/point/point_manager.dart';
import 'package:mypoint_flutter_app/screen/qr_code/qr_code_viewmodel.dart';
import 'package:mypoint_flutter_app/screen/qr_code/scan_code_screen.dart';
import 'package:mypoint_flutter_app/widgets/custom_navigation_bar.dart';
import 'package:mypoint_flutter_app/widgets/dashed_line.dart';
import 'package:qr_flutter/qr_flutter.dart';
import '../../base/base_screen.dart';
import '../../base/basic_state.dart';
import '../../preference/data_preference.dart';

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

  @override
  State<QRCodeScreen> createState() => _QRCodeScreenState();
}

class _QRCodeScreenState extends BaseState<QRCodeScreen> with BasicState {
  final _viewModel = Get.put(QRCodeViewModel());
  final _scanCtl = ScanTabController();

  int _tab = 0;
  final RxInt _points = 0.obs;
  final String _code = DataPreference.instance.profile?.workerSite?.id ?? '';
  final RxBool _isShowPoint = true.obs;

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

    _viewModel.onShowAlertError = (message) {
      if (message.isEmpty) {
        _scanCtl.resume();
        return;
      }
      _showAlertAndResumeScanCode(message);
    };
  }

  _freshPoint() async {
    _points.value = (await UserPointManager().fetchUserPoint()) ?? 0;
  }

  @override
  Widget createBody() {
    return Scaffold(
      appBar: CustomNavigationBar(title: _tab == 0 ? 'Mã tích điểm' : 'Quét mã'),
      backgroundColor: Color(0xFFF3F4F6),
      body: SafeArea(
        child: Stack(
          children: [
            _tab == 0 ? _buildYourCode() : _buildScanQRCode(),
            Positioned(
              top: 12,
              left: 16,
              right: 16,
              child: SegmentedTabs(
                tabs: const ['Mã của bạn', 'Quét mã'],
                index: _tab,
                onChanged: (i) => setState(() => _tab = i),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildYourCode() {
    final width = MediaQuery.of(context).size.width;
    return SingleChildScrollView(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: Column(
        children: [
          const SizedBox(height: 64),
          Image.asset('assets/images/ic_pipi_04.png', width: 120, height: 120),
          Container(
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(20),
              boxShadow: const [BoxShadow(color: Color(0x14000000), blurRadius: 16, offset: Offset(0, 6))],
            ),
            padding: const EdgeInsets.all(16),
            child: Column(
              children: [
                const Text(
                  'Vui lòng đưa nhân viên thu ngân quét mã để tích điểm',
                  textAlign: TextAlign.center,
                  style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: Color(0xFF0C2B4C)),
                ),
                const SizedBox(height: 12),
                BarcodeWidget(
                  barcode: Barcode.code128(),
                  data: _code,
                  width: double.infinity,
                  height: 80,
                  drawText: false,
                  color: Colors.black,
                  backgroundColor: Colors.white,
                  style: const TextStyle(fontSize: 14),
                ),
                const SizedBox(height: 16),
                QrImageView(
                  data: _code,
                  version: QrVersions.auto,
                  size: width / 1.7,
                  embeddedImage: const AssetImage('assets/images/ic_logo.png'),
                  embeddedImageStyle: const QrEmbeddedImageStyle(size: Size(64, 64)),
                ),
                const SizedBox(height: 12),
                DashedLine(),
                const SizedBox(height: 12),
                Row(
                  children: [
                    const Text(
                      'MyPoint',
                      style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: Color(0xFF0C2B4C)),
                    ),
                    const Spacer(),
                    Obx(
                      () => Row(
                        children: [
                          Image.asset('assets/images/ic_point.png', width: 24, height: 24),
                          const SizedBox(width: 6),
                          Text(
                            _isShowPoint.value ? '******' : _points.value.money(CurrencyUnit.point),
                            style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w700),
                          ),
                          const SizedBox(width: 6),
                          GestureDetector(
                            onTap: () {
                              setState(() {
                                _isShowPoint.toggle();
                              });
                            },
                            child: Icon(
                              _isShowPoint.value ? Icons.visibility_outlined : Icons.visibility_off_outlined,
                              color: Colors.black38,
                              size: 24,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  _showAlertAndResumeScanCode(String message) {
    showAlertError(
      content: message,
      showCloseButton: false,
      onConfirmed: () {
        _scanCtl.resume();
      },
    );
  }

  Widget _buildScanQRCode() {
    return ScanTabView(
      controller: _scanCtl,
      onCodeDetected: (code, format) async {
        final id = _viewModel.getResultCodeID(code) ?? '';
        // if (id.isEmpty) {
        //   final url = code.toUri();
        //   if (url == null) {
        //     _showAlertAndResumeScanCode('Mã QR không hợp lệ');
        //   } else {
        //     print('_buildScanQRCode $url');
        //     _scanCtl.resume();
        //   }
        //   return;
        // }
        _viewModel.getDirectionFromId(code);
      },
    );
  }
}

/// Segmented control (pill) giống iOS
class SegmentedTabs extends StatelessWidget {
  const SegmentedTabs({super.key, required this.tabs, required this.index, required this.onChanged});

  final List<String> tabs;
  final int index;
  final ValueChanged<int> onChanged;

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        decoration: BoxDecoration(color: Color(0x22000000), borderRadius: BorderRadius.circular(24)),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: List.generate(tabs.length, (i) {
            final selected = i == index;
            return SizedBox(
              width: 160,
              child: InkWell(
                borderRadius: BorderRadius.circular(20),
                onTap: () => onChanged(i),
                child: AnimatedContainer(
                  margin: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                  duration: const Duration(milliseconds: 180),
                  padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
                  decoration: BoxDecoration(
                    color: selected ? Colors.white : Colors.transparent,
                    borderRadius: BorderRadius.circular(20),
                    boxShadow:
                        selected
                            ? const [BoxShadow(color: Color(0x22000000), blurRadius: 8, offset: Offset(0, 3))]
                            : const [],
                  ),
                  child: Text(
                    tabs[i],
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      fontSize: 15,
                      fontWeight: FontWeight.w700,
                      color: selected ? const Color(0xFF0C2B4C) : Colors.white,
                    ),
                  ),
                ),
              ),
            );
          }),
        ),
      ),
    );
  }
}
