import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:onsolgo/core/constants.dart';
import 'package:onsolgo/core/achievement_manager.dart';
import 'package:url_launcher/url_launcher.dart';

class MarketHub extends StatelessWidget {
  const MarketHub({super.key});

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 3,
      child: Scaffold(
        backgroundColor: Colors.black,
        appBar: AppBar(
          title: const Text("ONSOL MARKET", style: TextStyle(letterSpacing: 2, fontWeight: FontWeight.bold)),
          centerTitle: true,
          bottom: const TabBar(
            indicatorColor: kOnsolGold, labelColor: kOnsolGold, unselectedLabelColor: Colors.grey,
            tabs: [Tab(text: "VAULT"), Tab(text: "PRINTS"), Tab(text: "MERCH")],
          ),
        ),
        body: const TabBarView(
          children: [
            _MarketCategoryView(categoryFilter: "vault"),
            _MarketCategoryView(categoryFilter: "prints"),
            _MarketCategoryView(categoryFilter: "merch"),
          ],
        ),
      ),
    );
  }
}

class _MarketCategoryView extends StatelessWidget {
  final String categoryFilter;
  const _MarketCategoryView({required this.categoryFilter});

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
      stream: FirebaseFirestore.instance.collection('marketplace').snapshots(),
      builder: (context, snapshot) {
        if (!snapshot.hasData) return const Center(child: CircularProgressIndicator());
        final filtered = snapshot.data!.docs.where((d) => d['category'] == categoryFilter).toList();

        return GridView.builder(
          padding: const EdgeInsets.all(16),
          gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2, childAspectRatio: 0.7, crossAxisSpacing: 16, mainAxisSpacing: 16),
          itemCount: filtered.length,
          itemBuilder: (context, index) {
            var p = filtered[index].data() as Map<String, dynamic>;
            return _ProductCard(name: p['name'], price: p['price'], imageUrl: p['imageUrl'], url: p['buyUrl']);
          },
        );
      },
    );
  }
}

class _ProductCard extends StatelessWidget {
  final String name, price, imageUrl, url;
  const _ProductCard({required this.name, required this.price, required this.imageUrl, required this.url});

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(color: Colors.grey[900], borderRadius: BorderRadius.circular(12)),
      child: Column(children: [
        Expanded(child: ClipRRect(borderRadius: const BorderRadius.vertical(top: Radius.circular(12)), child: CachedNetworkImage(imageUrl: imageUrl, fit: BoxFit.cover))),
        Padding(padding: const EdgeInsets.all(8.0), child: Column(children: [
          Text(name.toUpperCase(), style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 10)),
          Text(price, style: const TextStyle(color: kOnsolGold, fontSize: 12)),
          const SizedBox(height: 5),
          ElevatedButton(
            style: ElevatedButton.styleFrom(backgroundColor: Colors.white, foregroundColor: Colors.black, minimumSize: const Size(double.infinity, 30)),
            onPressed: () {
              launchUrl(Uri.parse(url));
              AchievementManager.unlock(FirebaseAuth.instance.currentUser!.uid, "first_acquisition");
            },
            child: const Text("ACQUIRE", style: TextStyle(fontSize: 10)),
          )
        ]))
      ]),
    );
  }
}