import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

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

  @override
  State<AdminPostScreen> createState() => _AdminPostScreenState();
}

class _AdminPostScreenState extends State<AdminPostScreen> {
  final _titleController = TextEditingController();
  final _contentController = TextEditingController();
  int _selectedMinTier = 1; // Default to Level 1 (Everyone)
  bool _isUploading = false;

  Future<void> _uploadPost() async {
    if (_titleController.text.isEmpty || _contentController.text.isEmpty) return;
    setState(() => _isUploading = true);

    try {
      await FirebaseFirestore.instance.collection('posts').add({
        'title': _titleController.text.trim(),
        'content': _contentController.text.trim(),
        'minTier': _selectedMinTier, // STORE THE REQUIRED LEVEL
        'timestamp': FieldValue.serverTimestamp(),
      });
      if (mounted) Navigator.pop(context);
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("ERROR: $e")));
    } finally {
      setState(() => _isUploading = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(title: const Text("INITIALIZE_LOG")),
      body: Padding(
        padding: const EdgeInsets.all(24.0),
        child: Column(
          children: [
            TextField(controller: _titleController, decoration: const InputDecoration(labelText: "LOG_TITLE")),
            const SizedBox(height: 15),
            TextField(controller: _contentController, maxLines: 5, decoration: const InputDecoration(labelText: "DATA_BODY")),
            const SizedBox(height: 25),

            // TIER SELECTOR
            const Align(alignment: Alignment.centerLeft, child: Text("REQUIRED_ACCESS_LEVEL:", style: TextStyle(color: Colors.white24, fontSize: 10))),
            DropdownButton<int>(
              value: _selectedMinTier,
              isExpanded: true,
              dropdownColor: Colors.black,
              style: const TextStyle(color: Color(0xFF00FF00), fontFamily: 'ShareTechMono'),
              items: const [
                DropdownMenuItem(value: 1, child: Text("LVL_01: OBSERVER (PUBLIC)")),
                DropdownMenuItem(value: 2, child: Text("LVL_02: COLLECTOR")),
                DropdownMenuItem(value: 3, child: Text("LVL_03: INVESTOR")),
              ],
              onChanged: (val) => setState(() => _selectedMinTier = val!),
            ),

            const Spacer(),
            _isUploading
                ? const CircularProgressIndicator(color: Color(0xFF00FF00))
                : ElevatedButton(onPressed: _uploadPost, child: const Text("[ BROADCAST_TO_VAULT ]")),
          ],
        ),
      ),
    );
  }
}