import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:hive_flutter/hive_flutter.dart';

import '../../app/icons/app_icons.dart';
import '../../app/theme/app_colors.dart';
import '../../data/local/hive_boxes.dart';
import '../../data/local/models/app_settings.dart';
import '../../data/services/notification_service.dart';
import '../../data/services/notification_inbox_service.dart';
import '../../features/dashboard/data/prayer_times_provider.dart';

class NotificationBellButton extends StatelessWidget {
  const NotificationBellButton({
    super.key,
    this.iconColor,
    this.iconSize = 22,
    this.onPressed,
    this.showBadge = true,
  });

  final Color? iconColor;
  final double iconSize;
  final VoidCallback? onPressed;
  final bool showBadge;

  @override
  Widget build(BuildContext context) {
    final inbox = NotificationInboxService.instance;
    return ValueListenableBuilder(
      valueListenable: inbox.listenable(),
      builder: (context, _, __) {
        final unread = showBadge ? inbox.unreadCount() : 0;
        return IconButton(
          onPressed: onPressed ??
              () {
                context.push('/notifications');
              },
          onLongPress: () => _showQuickActions(context),
          icon: Stack(
            clipBehavior: Clip.none,
            children: [
              AppIcon(
                glyph: AppIcons.notification,
                color: iconColor,
                size: iconSize,
              ),
              if (unread > 0)
                Positioned(
                  right: -6,
                  top: -4,
                  child: Container(
                    constraints:
                        const BoxConstraints(minWidth: 16, minHeight: 16),
                    padding: const EdgeInsets.symmetric(horizontal: 4),
                    decoration: BoxDecoration(
                      color: AppColors.errorLight,
                      borderRadius: BorderRadius.circular(99),
                      border: Border.all(
                        color: Theme.of(context).scaffoldBackgroundColor,
                        width: 1.4,
                      ),
                    ),
                    child: Center(
                      child: Text(
                        unread > 99 ? '99+' : '$unread',
                        style: const TextStyle(
                          color: Colors.white,
                          fontSize: 9,
                          height: 1,
                          fontWeight: FontWeight.w700,
                        ),
                      ),
                    ),
                  ),
                ),
            ],
          ),
        );
      },
    );
  }

  Future<void> _showQuickActions(BuildContext context) async {
    final settingsBox = Hive.box<AppSettings>(HiveBoxes.settings);
    final settings = settingsBox.get('default') ?? AppSettings();
    final alarmsOn = settings.adhanEnabled.values.any((v) => v);
    final isDark = Theme.of(context).brightness == Brightness.dark;

    await showModalBottomSheet<void>(
      context: context,
      backgroundColor:
          isDark ? AppColors.surfaceDarkElevated : AppColors.surfaceLight,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(22)),
      ),
      builder: (sheetContext) {
        return SafeArea(
          top: false,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const SizedBox(height: 8),
              Container(
                width: 44,
                height: 4,
                decoration: BoxDecoration(
                  color: isDark
                      ? AppColors.textSecondaryDark.withValues(alpha: 0.4)
                      : AppColors.textSecondaryLight.withValues(alpha: 0.3),
                  borderRadius: BorderRadius.circular(999),
                ),
              ),
              const SizedBox(height: 10),
              ListTile(
                leading: Icon(
                  alarmsOn
                      ? Icons.notifications_off_outlined
                      : Icons.notifications_active_outlined,
                ),
                title: Text(alarmsOn
                    ? 'Nonaktifkan Alarm Sholat'
                    : 'Aktifkan Alarm Sholat'),
                onTap: () async {
                  final container =
                      ProviderScope.containerOf(context, listen: false);
                  settings.adhanEnabled.updateAll((key, _) => !alarmsOn);
                  await settings.save();
                  if (alarmsOn) {
                    await NotificationService.instance.cancelAllPending();
                  }
                  container.invalidate(prayerTimesProvider);
                  unawaited(container.read(prayerTimesProvider.future));
                  if (sheetContext.mounted) Navigator.pop(sheetContext);
                },
              ),
              ListTile(
                leading: const Icon(Icons.sync_rounded),
                title: const Text('Sinkronkan Sekarang'),
                onTap: () {
                  final container =
                      ProviderScope.containerOf(context, listen: false);
                  container.invalidate(prayerTimesProvider);
                  unawaited(container.read(prayerTimesProvider.future));
                  if (sheetContext.mounted) Navigator.pop(sheetContext);
                },
              ),
              ListTile(
                leading: const Icon(Icons.settings_outlined),
                title: const Text('Buka Pengaturan'),
                onTap: () {
                  if (sheetContext.mounted) Navigator.pop(sheetContext);
                  context.push('/settings');
                },
              ),
              const SizedBox(height: 8),
            ],
          ),
        );
      },
    );
  }
}
