import 'package:flutter/material.dart';
import 'package:lanebow/screens/public_event/public_event_screen.dart';
import 'package:lanebow/services/public_event_service.dart';

class PublicEventEntryScreen extends StatefulWidget {
  final String publicHash;
  final PublicEventService? service;
  const PublicEventEntryScreen({super.key, required this.publicHash, this.service});

  @override
  State<PublicEventEntryScreen> createState() => _PublicEventEntryScreenState();
}

class _PublicEventEntryScreenState extends State<PublicEventEntryScreen> {
  late final PublicEventService _service = widget.service ?? PublicEventService();
  final TextEditingController _pw = TextEditingController();
  bool _loading = false;
  String? _error;
  bool _needPassword = false;

  @override
  void initState() {
    super.initState();
    // 자동 토큰 인증 시도
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _tryEnter();
    });
  }

  Future<void> _tryEnter({String? password}) async {
    setState(() {
      _loading = true;
      _error = null;
    });
    try {
      final data = await _service.enter(widget.publicHash, password: password);
      // 성공 시 토큰 저장은 서비스가 처리. 공개 화면으로 이동
      if (!mounted) return;
      Navigator.of(context).pushReplacement(
        MaterialPageRoute(builder: (_) => PublicEventScreen(publicHash: widget.publicHash)),
      );
    } catch (e) {
      // 401/needPassword 케이스 포함: 간단히 비번 입력 노출
      setState(() {
        _needPassword = true;
        _error = e.toString();
      });
    } finally {
      if (mounted) {
        setState(() {
          _loading = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('공개 이벤트 입장')),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('hash: ' + widget.publicHash),
            const SizedBox(height: 16),
            if (_loading) const LinearProgressIndicator(),
            if (_error != null) ...[
              Text(_error!, style: const TextStyle(color: Colors.red)),
              const SizedBox(height: 8),
            ],
            if (_needPassword) ...[
              TextField(
                key: const Key('public_password_field'),
                controller: _pw,
                decoration: const InputDecoration(labelText: '비밀번호'),
                obscureText: true,
              ),
              const SizedBox(height: 12),
              ElevatedButton(
                key: const Key('public_enter_submit'),
                onPressed: _loading
                    ? null
                    : () {
                        _tryEnter(password: _pw.text);
                      },
                child: const Text('입장'),
              ),
            ] else ...[
              const Text('자동 인증 시도 중...'),
            ],
          ],
        ),
      ),
    );
  }
}
