import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:kasy_kit/core/theme/theme.dart';
import 'package:kasy_kit/features/notifications/providers/models/notification.dart';
import 'package:kasy_kit/features/notifications/providers/notifications_provider.dart';
import 'package:kasy_kit/features/notifications/repositories/notifications_repository.dart';
import 'package:kasy_kit/features/settings/ui/widgets/settings_tile.dart';
import 'package:kasy_kit/i18n/translations.g.dart';

void showNotificationSettingsSheet(BuildContext context) {
  showModalBottomSheet<void>(
    context: context,
    useRootNavigator: true,
    backgroundColor: Colors.transparent,
    isScrollControlled: true,
    builder: (_) => const _NotificationSettingsSheet(),
  );
}

class _NotificationSettingsSheet extends ConsumerStatefulWidget {
  const _NotificationSettingsSheet();

  @override
  ConsumerState<_NotificationSettingsSheet> createState() =>
      _NotificationSettingsSheetState();
}

class _NotificationSettingsSheetState
    extends ConsumerState<_NotificationSettingsSheet> {
  NotificationPermission? _permission;
  bool _toggling = false;

  @override
  void initState() {
    super.initState();
    _loadPermission();
  }

  Future<void> _loadPermission() async {
    final p =
        await ref.read(notificationRepositoryProvider).getPermissionStatus();
    if (mounted) setState(() => _permission = p);
  }

  bool get _isEnabled => _permission is NotificationPermissionGranted;

  String _subtitle(BuildContext context) {
    final tr = context.t.notifications;
    return switch (_permission) {
      NotificationPermissionGranted() => tr.push_subtitle_enabled,
      NotificationPermissionDenied() => tr.push_subtitle_disabled,
      _ => tr.push_subtitle_waiting,
    };
  }

  Future<void> _onToggle(bool value) async {
    if (_toggling || _permission == null) return;
    setState(() => _toggling = true);
    await _permission!.maybeAsk();
    await _loadPermission();
    if (mounted) setState(() => _toggling = false);
  }

  Future<void> _markAllRead() async {
    await ref.read(notificationsProvider.notifier).readAll();
    if (mounted) Navigator.of(context).pop();
  }

  @override
  Widget build(BuildContext context) {
    final tr = context.t.notifications;
    final notificationsState = ref.watch(notificationsProvider);
    final hasUnread =
        notificationsState.value?.data.any((n) => !n.seen) ?? false;

    return Container(
      margin: EdgeInsets.only(
        left: KasySpacing.sm,
        right: KasySpacing.sm,
        bottom: MediaQuery.of(context).viewInsets.bottom +
            MediaQuery.of(context).padding.bottom +
            KasySpacing.sm,
      ),
      decoration: BoxDecoration(
        color: context.colors.background,
        borderRadius: KasyRadius.lgBorderRadius,
        border: Border.all(
          color: context.colors.outline.withValues(alpha: 0.5),
        ),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // drag handle
          Padding(
            padding: const EdgeInsets.only(top: KasySpacing.smd),
            child: Container(
              width: 36,
              height: 4,
              decoration: BoxDecoration(
                color: context.colors.onSurface.withValues(alpha: 0.14),
                borderRadius: KasyRadius.fullBorderRadius,
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.fromLTRB(
              KasySpacing.md,
              KasySpacing.md,
              KasySpacing.md,
              KasySpacing.smd,
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // Push toggle row
                SettingsSwitchTile(
                  icon: _isEnabled
                      ? KasyIcons.notificationActive
                      : KasyIcons.notification,
                  title: tr.push_title,
                  value: _isEnabled,
                  iconBackgroundColor: _isEnabled
                      ? const Color(0xFFFF6B35)
                      : const Color(0xFF78909C),
                  onChanged: _toggling ? (_) {} : _onToggle,
                ),
                // subtitle below
                Padding(
                  padding: const EdgeInsets.only(
                    left: 32 + KasySpacing.sm,
                    bottom: KasySpacing.xs,
                  ),
                  child: _permission == null
                      ? SizedBox(
                          height: 13,
                          width: 140,
                          child: LinearProgressIndicator(
                            borderRadius: BorderRadius.circular(4),
                            color: context.colors.primary.withValues(alpha: 0.25),
                            backgroundColor: context.colors.onSurface
                                .withValues(alpha: 0.06),
                          ),
                        )
                      : Text(
                          _subtitle(context),
                          style: context.textTheme.bodySmall?.copyWith(
                            color: context.colors.muted,
                          ),
                        ),
                ),
                if (hasUnread) ...[
                  const SettingsDivider(),
                  const SizedBox(height: KasySpacing.xs),
                  SettingsTile(
                    icon: KasyIcons.checkCircle,
                    title: tr.mark_all_read,
                    iconBackgroundColor: context.colors.primary,
                    onTap: _markAllRead,
                  ),
                ],
              ],
            ),
          ),
        ],
      ),
    );
  }
}
