import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:userfront/i18n.dart';
import 'package:userfront/core/ui/toast_service.dart';

import 'qr_scan_route.dart';

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

  @override
  State<QRScanScreen> createState() => _QRScanScreenState();
}

class _QRScanScreenState extends State<QRScanScreen> {
  final TextEditingController _controller = TextEditingController();

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

  void _submit() {
    final raw = _controller.text.trim();
    if (raw.isEmpty) {
      ToastService.info(
        tr('msg.userfront.qr.permission_required', fallback: '카메라 권한이 필요합니다.'),
      );
      return;
    }
    context.go(buildQrApprovePath(raw));
  }

  void _handleBack() {
    final router = GoRouter.of(context);
    if (router.canPop()) {
      router.pop();
      return;
    }
    router.go(buildQrBackFallbackPath());
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(tr('ui.userfront.qr.title', fallback: 'Scan QR Code')),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: _handleBack,
        ),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Text(
              tr(
                'msg.userfront.qr.permission_error',
                fallback: '카메라 권한 요청에 실패했습니다. 브라우저/OS 설정을 확인해주세요.',
              ),
            ),
            const SizedBox(height: 12),
            TextField(
              key: const ValueKey('qr_scan_manual_input'),
              controller: _controller,
              decoration: const InputDecoration(
                labelText: 'QR Payload',
                hintText: 'https://.../ql/{ref} 또는 ref',
              ),
              onSubmitted: (_) => _submit(),
            ),
            const SizedBox(height: 12),
            FilledButton.icon(
              key: const ValueKey('qr_scan_submit_button'),
              onPressed: _submit,
              icon: const Icon(Icons.check_circle),
              label: Text(
                tr('ui.userfront.qr.result_success', fallback: '승인 화면으로 이동'),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
