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

class EventsView extends StatefulWidget {
  const EventsView({super.key});
  @override
  State<EventsView> createState() => _EventsViewState();
}

class _EventsViewState extends State<EventsView> {
  static const Color terminalGreen = Color(0xFFE87D25);
  int _userTier = 1;

  @override
  void initState() {
    super.initState();
    _fetchTier();
  }

  Future<void> _fetchTier() async {
    final user = FirebaseAuth.instance.currentUser;
    if (user != null) {
      final doc = await FirebaseFirestore.instance.collection('users').doc(user.uid).get();
      if (mounted) setState(() => _userTier = doc.data()?['tier'] ?? 1);
    }
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
      stream: FirebaseFirestore.instance.collection('events').orderBy('date', descending: false).snapshots(),
      builder: (context, snapshot) {
        if (!snapshot.hasData) return const Center(child: CircularProgressIndicator(color: terminalGreen));
        final events = snapshot.data!.docs;

        if (events.isEmpty) return const Center(child: Text("NO_SCHEDULED_SESSIONS", style: TextStyle(color: Colors.white24)));

        return ListView.builder(
          padding: const EdgeInsets.all(16),
          itemCount: events.length,
          itemBuilder: (context, index) {
            final e = events[index].data() as Map<String, dynamic>;
            final int minTier = e['minTier'] ?? 1;

            // LOCK LOGIC
            if (_userTier < minTier) return _buildLockedEvent(minTier);

            return Container(
              margin: const EdgeInsets.only(bottom: 15),
              padding: const EdgeInsets.all(15),
              decoration: BoxDecoration(
                border: Border.all(color: terminalGreen.withValues(alpha: 0.3)),
                color: Colors.black,
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text("DATE: ${e['date_string'] ?? 'TBA'}", style: const TextStyle(color: terminalGreen, fontSize: 10)),
                  const SizedBox(height: 5),
                  Text(e['title'].toString().toUpperCase(), style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, letterSpacing: 2)),
                  Text("LOCATION: ${e['venue']} | ${e['city']}", style: const TextStyle(color: Colors.white70, fontSize: 12)),
                  const SizedBox(height: 15),
                  SizedBox(
                    width: double.infinity,
                    child: OutlinedButton(
                      style: OutlinedButton.styleFrom(
                        side: const BorderSide(color: terminalGreen),
                        shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
                      ),
                      onPressed: () async {
                        final Uri url = Uri.parse(e['link'] ?? "");
                        if (!await launchUrl(url)) {
                          ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text("LINK_ERROR")));
                        }
                      },
                      child: const Text("[ ACCESS_TICKETS ]"),
                    ),
                  ),
                ],
              ),
            );
          },
        );
      },
    );
  }

  Widget _buildLockedEvent(int tier) {
    return Container(
      margin: const EdgeInsets.only(bottom: 15),
      padding: const EdgeInsets.all(15),
      decoration: BoxDecoration(
        border: Border.all(color: Colors.white10),
        color: Colors.white.withValues(alpha: 0.02),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text("SESSION_ID: [ENCRYPTED]", style: TextStyle(color: Colors.white24, fontSize: 10)),
          const SizedBox(height: 5),
          const Text("REDACTED_EVENT_DATA", style: TextStyle(color: Colors.white12, fontSize: 16, letterSpacing: 1)),
          const SizedBox(height: 10),
          // FIXED VARIABLE INTERPOLATION HERE:
          Text("[ LVL_0${tier}_ACCESS_REQUIRED ]",
              style: const TextStyle(color: Colors.redAccent, fontSize: 10, fontWeight: FontWeight.bold)),
        ],
      ),
    );
  }
}