import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../models/preferences.dart';
import '../services/firestore_service.dart';

class SettingsScreen extends ConsumerWidget {
  const SettingsScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final prefsAsync = ref.watch(preferencesProvider);

    return prefsAsync.when(
      data: (prefs) => _buildSettings(context, ref, prefs),
      loading: () => const Center(
        child: Padding(
          padding: EdgeInsets.all(50),
          child: CircularProgressIndicator(),
        ),
      ),
      error: (e, st) => Center(child: Text('Error: $e')),
    );
  }

  Widget _buildSettings(
    BuildContext context,
    WidgetRef ref,
    AppPreferences prefs,
  ) {
    return ListView(
      padding: const EdgeInsets.all(16),
      children: [
        // Sheet header with drag handle
        Center(
          child: Container(
            width: 40,
            height: 4,
            margin: const EdgeInsets.only(bottom: 8),
            decoration: BoxDecoration(
              color: Colors.grey[300],
              borderRadius: BorderRadius.circular(2),
            ),
          ),
        ),
        // Title and close button
        Padding(
          padding: const EdgeInsets.symmetric(vertical: 8),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              const Text(
                'Settings',
                style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
              ),
              IconButton(
                icon: const Icon(Icons.close),
                onPressed: () => Navigator.of(context).pop(),
              ),
            ],
          ),
        ),
        const SizedBox(height: 8),
        Card(
          child: Column(
            children: [
              ListTile(
                leading: const Icon(Icons.volume_up),
                title: const Text('Voice Enabled'),
                subtitle: const Text('Enable voice input'),
                trailing: Switch(
                  value: prefs.voiceEnabled,
                  onChanged: (value) => _updatePreference(
                    context,
                    ref,
                    prefs.copyWith(voiceEnabled: value),
                  ),
                ),
              ),
              const Divider(height: 1),
              ListTile(
                leading: const Icon(Icons.record_voice_over),
                title: const Text('Voice Replies'),
                subtitle: const Text('AI speaks responses aloud'),
                trailing: Switch(
                  value: prefs.voiceRepliesEnabled,
                  onChanged: (value) {
                    print("🔵 Voice Replies toggle pressed: $value");
                    _updatePreference(
                      context,
                      ref,
                      prefs.copyWith(voiceRepliesEnabled: value),
                    );
                  },
                ),
              ),
            ],
          ),
        ),
        const SizedBox(height: 16),
        Card(
          child: Column(
            children: [
              ListTile(
                leading: const Icon(Icons.notifications),
                title: const Text('Gentle Nudges'),
                subtitle: const Text('Receive gentle reminders'),
                trailing: Switch(
                  value: prefs.gentleNudges,
                  onChanged: (value) => _updatePreference(
                    context,
                    ref,
                    prefs.copyWith(gentleNudges: value),
                  ),
                ),
              ),
              const Divider(height: 1),
              ListTile(
                leading: const Icon(Icons.shield),
                title: const Text('Focus Protection'),
                subtitle: const Text('Minimize interruptions'),
                trailing: Switch(
                  value: prefs.focusProtection,
                  onChanged: (value) => _updatePreference(
                    context,
                    ref,
                    prefs.copyWith(focusProtection: value),
                  ),
                ),
              ),
            ],
          ),
        ),
        const SizedBox(height: 16),
        Card(
          child: Column(
            children: [
              const Padding(
                padding: EdgeInsets.all(16),
                child: Align(
                  alignment: Alignment.centerLeft,
                  child: Text(
                    'Boundaries',
                    style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                  ),
                ),
              ),
              ...prefs.boundaries.entries.map((entry) {
                return CheckboxListTile(
                  title: Text(entry.key),
                  value: entry.value,
                  onChanged: (value) {
                    final newBoundaries = Map<String, bool>.from(
                      prefs.boundaries,
                    );
                    newBoundaries[entry.key] = value ?? false;
                    _updatePreference(
                      context,
                      ref,
                      prefs.copyWith(boundaries: newBoundaries),
                    );
                  },
                );
              }).toList(),
            ],
          ),
        ),
        _buildAboutSection(context),
      ],
    );
  }

  Widget _buildAboutSection(BuildContext context) {
    return Column(
      children: [
        const SizedBox(height: 24),
        const Divider(),
        const SizedBox(height: 16),
        Text(
          "About App",
          style: Theme.of(
            context,
          ).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold),
        ),
        const SizedBox(height: 8),
        const Text("Created by John Gai"),
        const SizedBox(height: 4),
        const Text(
          "CEO & Founder of barawave.com",
          style: TextStyle(color: Colors.grey, fontSize: 12),
        ),
        const SizedBox(height: 32),
      ],
    );
  }

  void _updatePreference(
    BuildContext context,
    WidgetRef ref,
    AppPreferences newPrefs,
  ) {
    print(
      "🔵 Updating preferences: voiceRepliesEnabled=${newPrefs.voiceRepliesEnabled}",
    );
    ref.read(firestoreServiceProvider).savePreferences(newPrefs);
    // Refresh the preferences
    ref.invalidate(preferencesProvider);

    // Show feedback
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('Settings saved'),
        duration: Duration(seconds: 1),
      ),
    );
  }
}
