import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:kasy_kit/core/dev_inspector/dev_inspector.dart';
import 'package:kasy_kit/core/icons/kasy_icons.dart';
import 'package:kasy_kit/core/rating/widgets/review_popup.dart';
import 'package:kasy_kit/core/states/user_state_notifier.dart';
import 'package:kasy_kit/core/toast/toast_service.dart';
import 'package:kasy_kit/core/web_device_preview/web_device_preview.dart';
import 'package:kasy_kit/core/widgets/update_bottom_sheet.dart';
import 'package:kasy_kit/features/notifications/api/local_notifier.dart';
import 'package:kasy_kit/features/settings/settings_page.dart';
import 'package:kasy_kit/features/settings/ui/components/admin/admin_routes.dart';
import 'package:kasy_kit/features/settings/ui/widgets/settings_tile.dart';
import 'package:kasy_kit/i18n/translations.g.dart';
import 'package:kasy_kit/router.dart';
import 'package:shared_preferences/shared_preferences.dart';

void showAdminBottomSheet(BuildContext context) {
  if (!kDebugMode) return;
  showModalBottomSheet<void>(
    context: context,
    useRootNavigator: true,
    isScrollControlled: true,
    enableDrag: false,
    backgroundColor: Colors.transparent,
    builder: (_) => const _AdminSheet(),
  );
}

/// Pushes an admin debug route without closing the sheet first.
///
/// When the route is popped, the sheet stays open (or is re-shown if the
/// platform dismissed it under the full-screen page).
Future<void> pushAdminDebugRouteFromSheet(
  BuildContext sheetContext,
  String route,
) async {
  await sheetContext.push(route);
  if (!sheetContext.mounted) {
    final BuildContext? settings = navigatorKey.currentContext;
    if (settings != null && settings.mounted) {
      showAdminBottomSheet(settings);
    }
  }
}

class _AdminSheet extends ConsumerWidget {
  const _AdminSheet();

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final userState = ref.watch(userStateNotifierProvider);
    // Leaves status bar + AppBar visible above the sheet
    final double sheetHeight = MediaQuery.of(context).size.height * 0.82;

    return SizedBox(
      height: sheetHeight,
      child: Container(
        decoration: BoxDecoration(
          color: Theme.of(context).scaffoldBackgroundColor,
          borderRadius: const BorderRadius.vertical(top: Radius.circular(16)),
        ),
        child: Column(
          children: [
            _SheetHandle(onClose: () => Navigator.pop(context)),
            Expanded(
              child: ListView(
                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                children: [
                  SettingsContainer(
                    child: Wrap(
                      children: [
                        ValueListenableBuilder<bool>(
                          valueListenable: devInspectorFabEnabledNotifier,
                          builder: (context, enabled, _) {
                            return SettingsSwitchTile(
                              icon: KasyIcons.widgets,
                              title: t.settings.admin.inspector_fab_title,
                              value: enabled,
                              onChanged: (v) async {
                                final p = await SharedPreferences.getInstance();
                                await p.setBool(devInspectorFabEnabledPrefKey, v);
                                devInspectorFabEnabledNotifier.value = v;
                              },
                            );
                          },
                        ),
                        if (kIsWeb) ...[
                          const SettingsDivider(),
                          ValueListenableBuilder<bool>(
                            valueListenable: webDevicePreviewEnabledNotifier,
                            builder: (context, enabled, _) {
                              return SettingsSwitchTile(
                                icon: KasyIcons.phoneAndroid,
                                title: t.settings.admin.device_preview_title,
                                value: enabled,
                                onChanged: (v) async {
                                  final navigator = Navigator.of(
                                    context,
                                    rootNavigator: true,
                                  );
                                  final p =
                                      await SharedPreferences.getInstance();
                                  await p.setBool(
                                    webDevicePreviewEnabledPrefKey,
                                    v,
                                  );
                                  webDevicePreviewEnabledNotifier.value = v;
                                  if (v) navigator.pop();
                                },
                              );
                            },
                          ),
                        ],
                        const SettingsDivider(),
                        SettingsTile(
                          icon: KasyIcons.note,
                          title: t.settings.admin.update_bottom_sheet,
                          onTap: () {
                            Navigator.pop(context);
                            showUpdateBottomSheet(
                              context: navigatorKey.currentContext!,
                              version: '0.0.0',
                            );
                          },
                        ),
                        const SettingsDivider(),
                        SettingsTile(
                          icon: KasyIcons.payment,
                          title: t.settings.admin.paywalls,
                          onTap: () => pushAdminDebugRouteFromSheet(
                            context,
                            adminRoutePaywalls,
                          ),
                        ),
                        const SettingsDivider(),
                        SettingsTile(
                          icon: KasyIcons.check,
                          title: t.settings.admin.test_onboarding,
                          onTap: () {
                            Navigator.pop(context);
                            ref.read(goRouterProvider).go('/onboarding');
                          },
                        ),
                        const SettingsDivider(),
                        SettingsTile(
                          icon: KasyIcons.person,
                          title: t.settings.admin.copy_user_id,
                          onTap: () {
                            Clipboard.setData(ClipboardData(
                              text: userState.user.idOrNull ?? 'no-id (guest)',
                            ));
                            ref.read(toastProvider).alert(
                              title: '',
                              text: t.settings.admin.user_id_copied,
                            );
                          },
                        ),
                        const SettingsDivider(),
                        SettingsTile(
                          icon: KasyIcons.notification,
                          title: t.settings.admin.copy_fcm_token,
                          onTap: () async {
                            final token =
                                await FirebaseMessaging.instance.getToken();
                            if (token == null) {
                              ref.read(toastProvider).alert(
                                title: '',
                                text: t.settings.admin.fcm_token_unavailable,
                              );
                              return;
                            }
                            await Clipboard.setData(
                              ClipboardData(text: token),
                            );
                            ref.read(toastProvider).alert(
                              title: '',
                              text: t.settings.admin.fcm_token_copied,
                            );
                          },
                        ),
                        const SettingsDivider(),
                        SettingsTile(
                          icon: KasyIcons.notificationActive,
                          title: t.settings.admin.ask_notification,
                          onTap: () {
                            Navigator.pop(context);
                            ref
                                .read(notificationsSettingsProvider)
                                .askPermission();
                          },
                        ),
                        const SettingsDivider(),
                        SettingsTile(
                          icon: KasyIcons.notificationActive,
                          title: t.settings.admin.send_push_title,
                          onTap: () => pushAdminDebugRouteFromSheet(
                            context,
                            adminRouteSendPush,
                          ),
                        ),
                        const SettingsDivider(),
                        SettingsTile(
                          icon: KasyIcons.star,
                          title: t.settings.admin.ask_review,
                          onTap: () =>
                              showReviewDialog(context, ref, force: true),
                        ),
                        const SettingsDivider(),
                        SettingsTile(
                          icon: KasyIcons.message,
                          title: t.settings.admin.home_widgets_panel,
                          onTap: () => pushAdminDebugRouteFromSheet(
                            context,
                            adminRouteHomeWidgets,
                          ),
                        ),
                      ],
                    ),
                  ),
                  const SizedBox(height: 24),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _SheetHandle extends StatelessWidget {
  final VoidCallback onClose;

  const _SheetHandle({required this.onClose});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      // Swipe down on the handle dismisses the sheet
      onVerticalDragEnd: (details) {
        if ((details.primaryVelocity ?? 0) > 200) onClose();
      },
      behavior: HitTestBehavior.opaque,
      child: Column(
        children: [
          const SizedBox(height: 12),
          Container(
            width: 36,
            height: 4,
            decoration: BoxDecoration(
              color: Theme.of(context).colorScheme.onSurface.withValues(alpha: 0.15),
              borderRadius: BorderRadius.circular(2),
            ),
          ),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
            child: Row(
              children: [
                Text(
                  'Admin',
                  style: Theme.of(context).textTheme.labelLarge?.copyWith(
                    color: Theme.of(context).colorScheme.onSurface.withValues(alpha: 0.4),
                    letterSpacing: 1.1,
                  ),
                ),
                const Spacer(),
                GestureDetector(
                  onTap: onClose,
                  behavior: HitTestBehavior.opaque,
                  child: Padding(
                    padding: const EdgeInsets.all(8),
                    child: Container(
                      width: 28,
                      height: 28,
                      decoration: BoxDecoration(
                        color: Theme.of(context).colorScheme.onSurface.withValues(alpha: 0.07),
                        shape: BoxShape.circle,
                      ),
                      child: Icon(
                        Icons.close,
                        size: 15,
                        color: Theme.of(context).colorScheme.onSurface.withValues(alpha: 0.5),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
          Divider(
            height: 1,
            color: Theme.of(context).colorScheme.onSurface.withValues(alpha: 0.07),
          ),
        ],
      ),
    );
  }
}
