import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:mobile_scanner/mobile_scanner.dart';

import '../../../core/l10n/app_localizations.dart';

/// 二维码扫描页面
///
/// 依赖: mobile_scanner: ^4.0.0
///
/// 在 pubspec.yaml 中添加:
/// dependencies:
///   mobile_scanner: ^4.0.0
class QrScannerScreen extends StatefulWidget {
  const QrScannerScreen({super.key});

  @override
  State<QrScannerScreen> createState() => _QrScannerScreenState();
}

class _QrScannerScreenState extends State<QrScannerScreen> {
  final MobileScannerController _controller = MobileScannerController();
  bool _hasResult = false;

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final cs = Theme.of(context).colorScheme;

    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: const Icon(Icons.chevron_left, size: 28),
          onPressed: () => context.pop(),
        ),
        title: Text(AppLocalizations.of(context)!.scanQrCode, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w600)),
        centerTitle: true,
      ),
      body: _buildScannerBody(context, cs),
    );
  }

  Widget _buildScannerBody(BuildContext context, ColorScheme cs) {
    return MobileScanner(
      controller: _controller,
      onDetect: (capture) {
        if (_hasResult) return;
        for (final barcode in capture.barcodes) {
          final value = barcode.rawValue;
          if (value != null && value.isNotEmpty) {
            _hasResult = true;
            _controller.stop();
            context.pop(value);
            break;
          }
        }
      },
    );
  }
}
