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';
import 'admin_artifact_screen.dart';

class ArtifactsView extends StatelessWidget {
  const ArtifactsView({super.key});
  static const Color terminalGreen = Color(0xFFE87D25);

  // --- ADMIN LOGIC: DELETE ARTIFACT ---
  Future<void> _deleteArtifact(BuildContext context, String docId, String title) async {
    bool confirm = await showDialog(
      context: context,
      builder: (context) => AlertDialog(
        backgroundColor: Colors.black,
        shape: const RoundedRectangleBorder(side: BorderSide(color: Colors.red)),
        title: const Text("CONFIRM_ERASURE", style: TextStyle(color: Colors.red, fontSize: 14)),
        content: Text("ARE YOU SURE YOU WANT TO REMOVE $title FROM THE VAULT?"),
        actions: [
          TextButton(onPressed: () => Navigator.pop(context, false), child: const Text("[ CANCEL ]")),
          TextButton(
              onPressed: () => Navigator.pop(context, true),
              child: const Text("[ DELETE ]", style: TextStyle(color: Colors.red))
          ),
        ],
      ),
    ) ?? false;

    if (confirm) {
      await FirebaseFirestore.instance.collection('artifacts').doc(docId).delete();
    }
  }

  @override
  Widget build(BuildContext context) {
    final user = FirebaseAuth.instance.currentUser;

    return StreamBuilder<DocumentSnapshot>(
      stream: FirebaseFirestore.instance.collection('users').doc(user?.uid).snapshots(),
      builder: (context, userSnapshot) {
        bool isAdmin = false;
        if (userSnapshot.hasData && userSnapshot.data!.exists) {
          final data = userSnapshot.data!.data() as Map<String, dynamic>;
          isAdmin = data['role'] == 'admin';
        }

        return Column(
          children: [
            if (isAdmin)
              Padding(
                padding: const EdgeInsets.all(12.0),
                child: OutlinedButton(
                  style: OutlinedButton.styleFrom(
                    minimumSize: const Size(double.infinity, 45),
                    side: const BorderSide(color: terminalGreen),
                    shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
                  ),
                  onPressed: () => Navigator.push(
                      context,
                      MaterialPageRoute(builder: (context) => const AdminArtifactScreen())
                  ),
                  child: const Text("[ REGISTER_NEW_ARTIFACT ]"),
                ),
              ),

            Expanded(
              child: StreamBuilder<QuerySnapshot>(
                stream: FirebaseFirestore.instance
                    .collection('artifacts')
                    .orderBy('createdAt', descending: true)
                    .snapshots(),
                builder: (context, snapshot) {
                  if (!snapshot.hasData) return const Center(child: CircularProgressIndicator(color: terminalGreen));
                  final docs = snapshot.data!.docs;

                  if (docs.isEmpty) return const Center(child: Text("INVENTORY_NULL / AWAITING_DROP"));

                  return ListView.builder(
                    itemCount: docs.length,
                    padding: const EdgeInsets.only(bottom: 20),
                    itemBuilder: (context, index) {
                      final String docId = docs[index].id;
                      final item = docs[index].data() as Map<String, dynamic>;
                      return _buildArtifactCard(context, item, docId, isAdmin);
                    },
                  );
                },
              ),
            ),
          ],
        );
      },
    );
  }

  Widget _buildArtifactCard(BuildContext context, Map data, String docId, bool isAdmin) {
    final int stock = int.tryParse(data['stock'].toString()) ?? 0;
    final bool isSoldOut = stock <= 0;
    final String title = data['title'].toString().toUpperCase();

    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
      decoration: BoxDecoration(
        border: Border.all(color: terminalGreen.withValues(alpha: 0.2)),
        color: Colors.black,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // IMAGE SECTION
          Stack(
            children: [
              AspectRatio(
                aspectRatio: 1,
                child: Image.network(
                  data['imageUrl'],
                  fit: BoxFit.cover,
                  errorBuilder: (context, error, stackTrace) => const Icon(Icons.broken_image, color: terminalGreen),
                ),
              ),
              // DELETE BUTTON (ONLY FOR ADMIN)
              if (isAdmin)
                Positioned(
                  top: 10,
                  right: 10,
                  child: IconButton(
                    style: IconButton.styleFrom(backgroundColor: Colors.black54),
                    icon: const Icon(Icons.delete_forever, color: Colors.red),
                    onPressed: () => _deleteArtifact(context, docId, title),
                  ),
                ),
            ],
          ),
          Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Expanded(
                      child: Text(
                        title,
                        style: const TextStyle(fontSize: 15, fontWeight: FontWeight.bold, letterSpacing: 1.2, height: 1.3),
                        softWrap: true,
                      ),
                    ),
                    const SizedBox(width: 12),
                    Text("\$${data['price']}", style: const TextStyle(color: terminalGreen, fontSize: 18, fontWeight: FontWeight.bold)),
                  ],
                ),
                const SizedBox(height: 15),
                Text("SERIAL: ${data['serial']}", style: const TextStyle(color: Colors.white24, fontSize: 10)),
                Text(
                  isSoldOut ? "STATUS: DEPLETED" : "UNITS_AVAIL: $stock",
                  style: TextStyle(color: isSoldOut ? Colors.red : terminalGreen, fontSize: 10),
                ),
                const SizedBox(height: 15),
                Text(data['description'] ?? "", style: const TextStyle(color: Colors.white70, fontSize: 13, height: 1.4)),
                const SizedBox(height: 25),

                SizedBox(
                  width: double.infinity,
                  height: 50,
                  child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: isSoldOut ? Colors.grey[900] : Colors.black,
                      side: BorderSide(color: isSoldOut ? Colors.white12 : terminalGreen),
                      shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
                    ),
                    onPressed: isSoldOut ? null : () async {
                      final Uri url = Uri.parse(data['purchaseUrl'] ?? "https://savexstate.com");
                      if (!await launchUrl(url, mode: LaunchMode.externalApplication)) {
                        ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text("ERROR: LINK_FAILURE")));
                      }
                    },
                    child: Text(
                      isSoldOut ? "[ ASSET_DEPLETED ]" : "[ ACQUIRE_ASSET ]",
                      style: TextStyle(color: isSoldOut ? Colors.grey : terminalGreen),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}