import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:onsolgo/core/constants.dart';
import 'package:onsolgo/screens/library/series_detail.dart';

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: CustomScrollView(
        slivers: [
          // THE BRAND BANNER
          SliverToBoxAdapter(
            child: Container(
              color: Colors.black,
              padding: const EdgeInsets.only(top: 50, bottom: 10),
              child: CachedNetworkImage(
                  imageUrl: kOnsolBanner,
                  height: 100,
                  fit: BoxFit.contain
              ),
            ),
          ),

          // THE MANAA GRID
          StreamBuilder<QuerySnapshot>(
            stream: FirebaseFirestore.instance.collection('manga').snapshots(),
            builder: (context, snapshot) {
              if (snapshot.hasError) return const SliverToBoxAdapter(child: Center(child: Text("Error Connection")));
              if (!snapshot.hasData) return const SliverToBoxAdapter(child: Center(child: CircularProgressIndicator()));

              final docs = snapshot.data!.docs;

              return SliverPadding(
                padding: const EdgeInsets.all(16),
                sliver: SliverGrid(
                  gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 2,
                      childAspectRatio: 0.65,
                      crossAxisSpacing: 16,
                      mainAxisSpacing: 20
                  ),
                  delegate: SliverChildBuilderDelegate(
                        (context, index) => _MangaGridCard(manga: docs[index]),
                    childCount: docs.length,
                  ),
                ),
              );
            },
          ),
        ],
      ),
    );
  }
}

class _MangaGridCard extends StatelessWidget {
  final QueryDocumentSnapshot manga;
  const _MangaGridCard({required this.manga});

  @override
  Widget build(BuildContext context) {
    final mData = manga.data() as Map<String, dynamic>;

    return GestureDetector(
      onTap: () => Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => SeriesDetail(manga: manga))
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(
            child: Stack(
              children: [
                ClipRRect(
                  borderRadius: BorderRadius.circular(12),
                  child: CachedNetworkImage(
                    imageUrl: mData['coverUrl'] ?? '',
                    fit: BoxFit.cover,
                    width: double.infinity,
                    alignment: Alignment.topCenter,
                    // Fix for desaturation: Ensure no filters are applied
                    placeholder: (context, url) => Container(color: Colors.grey[900]),
                  ),
                ),
                // READ COUNT OVERLAY
                Positioned(
                  bottom: 8, left: 8,
                  child: Container(
                    padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 3),
                    decoration: BoxDecoration(
                        color: Colors.black.withValues(alpha: 0.7),
                        borderRadius: BorderRadius.circular(4)
                    ),
                    child: Row(
                      children: [
                        const Icon(Icons.remove_red_eye, size: 12, color: Colors.white),
                        const SizedBox(width: 4),
                        Text(
                            "${safeInt(mData['reads'])}",
                            style: const TextStyle(fontSize: 10, color: Colors.white, fontWeight: FontWeight.bold)
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(height: 10),
          Text(
              mData['title'].toString().toUpperCase(),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 13, color: Colors.white)
          ),
          Text(
            mData['author'] ?? 'Artist',
            style: const TextStyle(fontSize: 11, color: Colors.grey),
          ),
        ],
      ),
    );
  }
}