// SPDX-FileCopyrightText: © 2025 Nøkken.io <nokken.io@proton.me>
// SPDX-License-Identifier: AGPL-3.0
//
//  settings_screen.dart
//
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:nokken/src/features/settings/screens/admin_screen.dart';
import 'package:nokken/src/core/ui/theme/app_icons.dart';
import 'package:nokken/src/core/ui/theme/providers/theme_provider.dart';
import 'package:nokken/src/core/ui/widgets/shared_widgets.dart';
import 'package:nokken/src/core/ui/theme/app_colors.dart';
import 'package:nokken/src/core/ui/theme/app_text_styles.dart';
import 'package:nokken/src/core/services/database/database_service.dart';

class SettingsScreen extends ConsumerWidget {
  const SettingsScreen({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    // Watch the theme provider to react to theme changes
    final themeMode = ref.watch(themeProvider);
    final isDarkMode = themeMode == ThemeMode.dark;

    return Scaffold(
      appBar: AppBar(
        title: Text('Settings', style: AppTextStyles.headlineSmall),
        backgroundColor: AppColors.primary,
      ),
      body: Container(
        color: AppColors.surface,
        child: ListView(
          children: [
            // Display settings section
            SharedWidgets.buildSectionHeader('Display'),

            // Theme toggle
            _buildSettingItem(
              context,
              title: 'Dark Mode',
              subtitle: isDarkMode ? 'On' : 'Off',
              icon: Icons.dark_mode,
              trailing: Switch(
                value: isDarkMode,
                onChanged: (value) {
                  // Toggle theme
                  ThemeUtils.setTheme(
                      ref, value ? ThemeMode.dark : ThemeMode.light);
                },
                activeColor: AppColors.primary,
              ),
            ),

            // Divider
            Divider(color: AppColors.outline),

            // Debug section - ONLY FOR DEVELOPMENT
            SharedWidgets.buildSectionHeader('Developer Options'),

            // Database debug button
            _buildSettingItem(
              context,
              title: 'Debug Database',
              subtitle: 'Check mood entries table',
              icon: Icons.bug_report,
              onTap: () => _showDatabaseDebugInfo(context),
            ),

            // Admin tools button
            _buildSettingItem(
              context,
              title: 'Admin Tools',
              subtitle: 'Data generation and management',
              icon: Icons.admin_panel_settings,
              onTap: () => Navigator.of(context).push(
                MaterialPageRoute(
                  builder: (context) => const AdminScreen(),
                ),
              ),
            ),

            // Divider
            Divider(color: AppColors.outline),

            // About section
            SharedWidgets.buildSectionHeader('About'),

            // App version
            _buildSettingItem(
              context,
              title: 'Version',
              subtitle: '0.0.1',
              icon: AppIcons.getIcon('info'),
            ),
          ],
        ),
      ),
    );
  }
}

/// Helper method to build consistent setting items
Widget _buildSettingItem(
  BuildContext context, {
  required String title,
  required IconData icon,
  String? subtitle,
  Widget? trailing,
  VoidCallback? onTap,
}) {
  return ListTile(
    leading: Icon(icon, color: AppColors.primary),
    title: Text(title, style: AppTextStyles.titleMedium),
    subtitle: subtitle != null
        ? Text(subtitle, style: AppTextStyles.bodySmall)
        : null,
    trailing: trailing,
    onTap: onTap,
    contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
  );
}

Future<void> _showDatabaseDebugInfo(BuildContext context) async {
  // Show loading dialog
  showDialog(
    context: context,
    barrierDismissible: false,
    builder: (context) => const Center(
      child: CircularProgressIndicator(),
    ),
  );

  try {
    // Get the database service
    final dbService = DatabaseService();
    final debugInfo = await dbService.getDebugInfo();

    // Close loading dialog
    // ignore: use_build_context_synchronously
    Navigator.of(context).pop();

    // Show debug info dialog
    showDialog(
      // ignore: use_build_context_synchronously
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Database Debug Info'),
        content: SingleChildScrollView(
          child: Text(debugInfo),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('Close'),
          ),
        ],
      ),
    );
  } catch (e) {
    // Close loading dialog
    // ignore: use_build_context_synchronously
    Navigator.of(context).pop();

    // Show error dialog
    showDialog(
      // ignore: use_build_context_synchronously
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Error'),
        content: Text('Failed to get debug info: $e'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('Close'),
          ),
        ],
      ),
    );
  }
}
