import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
class InviteSignupScreen extends StatefulWidget {
  const InviteSignupScreen({super.key});
  @override
  State<InviteSignupScreen> createState() => _InviteSignupScreenState();
}

class _InviteSignupScreenState extends State<InviteSignupScreen> {
  final _code = TextEditingController();
  final _email = TextEditingController();
  final _pass = TextEditingController();
  final _user = TextEditingController();

  void _processSignup() async {
    final messenger = ScaffoldMessenger.of(context);
    final nav = Navigator.of(context);
    // 1. Check if Invite Code exists and is not used
    var codeDoc = await FirebaseFirestore.instance.collection('invite_codes').doc(_code.text.trim()).get();

    final codeData = codeDoc.data();
    if (codeDoc.exists && codeData != null && codeData['isUsed'] == false) {
      try {
        // 2. Create the User
        UserCredential cred = await FirebaseAuth.instance.createUserWithEmailAndPassword(
            email: _email.text.trim(), password: _pass.text.trim());

        // 3. Create Firestore Profile
        await FirebaseFirestore.instance.collection('users').doc(cred.user!.uid).set({
          'username': _user.text.trim(),
          'role': 'reader',
          'rankLevel': 1,
          'uid': cred.user!.uid,
        });

        // 4. Burn the code
        await codeDoc.reference.update({'isUsed': true});

        if (context.mounted) nav.pop();
      } catch (e) {
        messenger.showSnackBar(SnackBar(content: Text(e.toString())));
      }
    } else {
      messenger.showSnackBar(const SnackBar(content: Text("Invalid or Used Code")));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("REDEEM INVITATION")),
      body: ListView(
        padding: const EdgeInsets.all(32),
        children: [
          TextField(controller: _code, decoration: const InputDecoration(labelText: "6-Digit Invite Code")),
          TextField(controller: _user, decoration: const InputDecoration(labelText: "Choose Username")),
          TextField(controller: _email, decoration: const InputDecoration(labelText: "Email")),
          TextField(controller: _pass, decoration: const InputDecoration(labelText: "Password"), obscureText: true),
          const SizedBox(height: 30),
          ElevatedButton(onPressed: _processSignup, child: const Text("JOIN THE ORDER")),
        ],
      ),
    );
  }
}