import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:proxibuy/core/config/app_colors.dart';
import 'package:proxibuy/core/gen/assets.gen.dart';
import 'package:proxibuy/presentation/notification_preferences/bloc/notification_preferences_bloc.dart';
import 'package:proxibuy/presentation/notification_preferences/bloc/notification_preferences_event.dart';
import 'package:proxibuy/presentation/notification_preferences/bloc/notification_preferences_state.dart';
import 'package:proxibuy/presentation/offer/bloc/offer_bloc.dart';
import 'package:proxibuy/presentation/offer/bloc/offer_event.dart';
import 'package:proxibuy/presentation/pages/offers_page.dart';
import 'package:proxibuy/presentation/widgets/category_selection_card.dart';
import 'package:shared_preferences/shared_preferences.dart';

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

  static Route<void> route() {
    return MaterialPageRoute<void>(
      builder: (_) => const NotificationPreferencesPage(),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        automaticallyImplyLeading: false,
        title: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 15.0, vertical: 0.0),
          child: Assets.icons.logoWithName.svg(height: 40, width: 200),
        ),
        actions: [
          IconButton(
            onPressed: () {
              // TODO: Navigate to notifications page
            },
            icon: Assets.icons.notification.svg(),
          ),
          IconButton(
            onPressed: () {
              // TODO: Navigate to QR codes page
            },
            icon: Assets.icons.scanBarcode.svg(),
          ),
          const SizedBox(width: 8),
        ],
      ),
      body: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              'دریافت اعلان',
              style: TextStyle(
                fontFamily: 'Dana',
                fontSize: 20,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 4),
            const Divider(),
            RichText(
              text: TextSpan(
                style: TextStyle(
                  fontFamily: 'Dana',
                  fontSize: 14,
                  color: AppColors.hint,
                  height: 1.5,
                ),
                children: const <TextSpan>[
                  TextSpan(
                    text:
                        'ترجیح می‌دی از کدام دسته‌بندی‌ها اعلان تخفیف دریافت کنی؟ ',
                    style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
                  ),
                  TextSpan(text: '(حداقل یک مورد رو انتخاب کن).'),
                ],
              ),
            ),
            const SizedBox(height: 24),
            Expanded(
              child: BlocBuilder<
                NotificationPreferencesBloc,
                NotificationPreferencesState
              >(
                builder: (context, state) {
                  if (state.categories.isEmpty) {
                    return const Center(child: CircularProgressIndicator());
                  }

                  const double sidePadding = 24.0;
                  const double crossAxisSpacing = 16.0;
                  const int crossAxisCount = 3;
                  const double mainAxisSpacing = 24.0;
                  const double childAspectRatio = 0.9;
                  final screenWidth = MediaQuery.of(context).size.width;

                  final totalHorizontalPadding = sidePadding * 2;
                  final totalSpacing = crossAxisSpacing * (crossAxisCount - 1);
                  final availableWidth = screenWidth - totalHorizontalPadding;
                  final itemWidth =
                      (availableWidth - totalSpacing) / crossAxisCount;
                  final itemHeight = itemWidth / childAspectRatio;

                  return SingleChildScrollView(
                    child: Wrap(
                      alignment: WrapAlignment.center,
                      spacing: crossAxisSpacing,
                      runSpacing: mainAxisSpacing,
                      children:
                          state.categories.map((category) {
                            final isSelected = state.selectedCategoryIds
                                .contains(category.id);
                            return SizedBox(
                              width: itemWidth,
                              height: itemHeight,
                              child: CategorySelectionCard(
                                name: category.name,
                                icon: category.icon,
                                isSelected: isSelected,
                                showSelectableIndicator:
                                    state.selectedCategoryIds.isNotEmpty,
                                onTap: () {
                                  context
                                      .read<NotificationPreferencesBloc>()
                                      .add(
                                        ToggleCategorySelection(category.id),
                                      );
                                },
                              ),
                            );
                          }).toList(),
                    ),
                  );
                },
              ),
            ),
            BlocBuilder<
              NotificationPreferencesBloc,
              NotificationPreferencesState
            >(
              builder: (context, state) {
                final isEnabled = state.selectedCategoryIds.isNotEmpty;
                return SizedBox(
                  width: double.infinity,
                  child:
                      isEnabled
                          ? ElevatedButton(
                            onPressed:
                                isEnabled
                                    ? () async {
                                      final selectedCategoryNames =
                                          state.categories
                                              .where(
                                                (cat) => state
                                                    .selectedCategoryIds
                                                    .contains(cat.id),
                                              )
                                              .map((cat) => cat.name)
                                              .toList();

                                      final prefs =
                                          await SharedPreferences.getInstance();
                                      await prefs.setStringList(
                                        'user_selected_categories',
                                        selectedCategoryNames,
                                      );

                                      if (context.mounted) {
                                        context.read<OffersBloc>().add(
                                          OffersFetchRequested(
                                            selectedCategories:
                                                selectedCategoryNames,
                                          ),
                                        );
                                      }

                                      if (!context.mounted) return;

                                      Navigator.pushReplacement(
                                        context,
                                        MaterialPageRoute(
                                          builder:
                                              (context) => const OffersPage(
                                                showDialogsOnLoad: true,
                                              ),
                                        ),
                                      );
                                    }
                                    : null,
                            style: ElevatedButton.styleFrom(
                              backgroundColor: AppColors.confirm,
                              foregroundColor: Colors.white,
                              disabledBackgroundColor: Colors.grey,
                              padding: const EdgeInsets.symmetric(vertical: 16),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(50),
                              ),
                            ),
                            child: const Text(
                              'اعمال',
                              style: TextStyle(
                                fontFamily: 'Dana',
                                fontSize: 16,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          )
                          : const SizedBox(),
                );
              },
            ),
            const SizedBox(height: 40),
          ],
        ),
      ),
    );
  }
}
