import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:hum/core/constants/app_text.dart';
import 'package:hum/core/constants/app_theme.dart';
import 'package:hum/core/utils/icon_mapper.dart';
import 'package:phosphor_flutter/phosphor_flutter.dart';

class HomePanelCategory extends StatefulWidget {
  final List<Map<String, dynamic>> categories;
  const HomePanelCategory({super.key, this.categories = const []});

  @override
  State<HomePanelCategory> createState() => _HomePanelCategoryState();
}

Stream<List<Map<String, dynamic>>> categoriesStream() {
  return FirebaseFirestore.instance
      .collection('categories')
      .snapshots()
      .map((snapshot) => snapshot.docs.map((doc) => doc.data()).toList());
}

class _HomePanelCategoryState extends State<HomePanelCategory> {
  List<String> selectedCategories = [];

  bool isSelected(String categoryId, int index) {
    if (selectedCategories.contains(categoryId)) {
      return true;
    } else if (index == 0 && selectedCategories.isEmpty) {
      return true;
    }
    return false;
  }

  void toggleCategory(String category) {
    if (category.toLowerCase() == 'all') {
      selectedCategories.clear();
      setState(() => selectedCategories = selectedCategories);
      return;
    }

    if (selectedCategories.contains(category)) {
      selectedCategories.remove(category);
    } else {
      selectedCategories.add(category);
    }

    setState(() => selectedCategories = selectedCategories);
  }

  @override
  Widget build(BuildContext context) {
    return CupertinoPageScaffold(
      backgroundColor: CupertinoDynamicColor.resolve(colorBarBackground, context),
      navigationBar: CupertinoNavigationBar(
        automaticallyImplyLeading: false,
        trailing: CupertinoButton(
          padding: EdgeInsets.all(0),
          child: Text(doneLabel),
          onPressed: () => Navigator.of(context).maybePop(),
        ),
      ),

      child: SafeArea(
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 16.0),
          child: CustomScrollView(
            physics: const BouncingScrollPhysics(),
            slivers: [
              SliverPadding(
                padding: const EdgeInsets.only(top: 12, bottom: 24),
                sliver: SliverGrid(
                  gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 2,
                    mainAxisSpacing: 8,
                    crossAxisSpacing: 8,
                    childAspectRatio: 1.7, // width / height ratio
                  ),
                  delegate: SliverChildBuilderDelegate((context, index) {
                    final category = widget.categories[index];

                    return GestureDetector(
                      onTap: () {
                        toggleCategory(category['id']);
                      },
                      child: Container(
                        decoration: BoxDecoration(
                          color: CupertinoDynamicColor.resolve(
                            (isSelected(category['id'], index))
                                ? colorBarControl.withAlpha(30)
                                : colorBarControl.withAlpha(10),
                            context,
                          ),
                          borderRadius: BorderRadius.circular(12),
                          border: BoxBorder.all(
                            width: 2,
                            color: (isSelected(category['id'], index))
                                ? CupertinoColors.activeGreen
                                : colorBarControlBordeer.withValues(alpha: 0.2),
                          ),
                        ),
                        child: Center(
                          child: Column(
                            spacing: 10,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              PhosphorIcon(
                                PhosphorIconHelper.fromString(
                                  category['icon'] ?? 'home',
                                  style: (isSelected(category['id'], index)) ? 'fill' : 'duotone',
                                ),
                                size: 40,
                                color: (isSelected(category['id'], index))
                                    ? CupertinoColors.activeGreen
                                    : CupertinoColors.white.withAlpha(140),
                              ),

                              Text(
                                category['name'] ?? 'Unnamed',
                                style: TextStyle(
                                  color: (isSelected(category['id'], index))
                                      ? CupertinoColors.activeGreen
                                      : CupertinoColors.white.withAlpha(180),
                                  fontSize: 16,
                                  fontWeight: FontWeight.w500,
                                ),
                                textAlign: TextAlign.center,
                              ),
                            ],
                          ),
                        ),
                      ),
                    );
                  }, childCount: widget.categories.length),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
