import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../l10n/app_localizations.dart';
import '../providers/providers.dart';

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

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final userProfile = ref.watch(userProfileProvider);
    final languageAsync = ref.watch(languageProvider);
    final themeMode = ref.watch(themeModeProvider);
    final l10n = AppLocalizations.of(context);

    final language = languageAsync.maybeWhen(
      data: (value) => value,
      orElse: () => 'system',
    );

    return Scaffold(
      appBar: AppBar(
        title: Text(l10n.settings),
      ),
      body: ListView(
        children: [
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  l10n.profile,
                  style: Theme.of(context).textTheme.titleMedium,
                ),
                const SizedBox(height: 16),
                userProfile.when(
                  data: (profile) {
                    if (profile == null) {
                      return Text(l10n.noProfileInfo);
                    }
                    return Card(
                      child: Padding(
                        padding: const EdgeInsets.all(16.0),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              children: [
                                CircleAvatar(
                                  radius: 32,
                                  child: Text(
                                    profile.firstName[0].toUpperCase(),
                                    style: Theme.of(context).textTheme.titleLarge,
                                  ),
                                ),
                                const SizedBox(width: 16),
                                Expanded(
                                  child: Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      Text(
                                        profile.fullName,
                                        style: Theme.of(context).textTheme.titleMedium,
                                      ),
                                      const SizedBox(height: 4),
                                      Text(
                                        profile.email,
                                        style: Theme.of(context).textTheme.bodySmall,
                                      ),
                                    ],
                                  ),
                                ),
                                IconButton.filled(
                                  icon: const Icon(Icons.logout),
                                  onPressed: () async {
                                    final authService = ref.read(authServiceProvider);
                                    await authService.logout();
                                    if (context.mounted) {
                                      // ignore: unused_result
                                      ref.refresh(isAuthenticatedProvider);
                                      if (context.mounted) {
                                        Navigator.of(context).pushReplacementNamed('/');
                                      }
                                    }
                                  },
                                  color: Theme.of(context).colorScheme.error,
                                  tooltip: l10n.logout,
                                ),
                              ],
                            ),
                          ],
                        ),
                      ),
                    );
                  },
                  loading: () => const CircularProgressIndicator(),
                  error: (error, stackTrace) => Text(l10n.error(error.toString())),
                ),
              ],
            ),
          ),
          const Divider(),
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  l10n.preferences,
                  style: Theme.of(context).textTheme.titleMedium,
                ),
                const SizedBox(height: 16),
                ListTile(
                  title: Text(l10n.language),
                  subtitle: Text(
                    language == 'system'
                        ? l10n.systemLanguage
                        : language == 'fr'
                            ? l10n.french
                            : l10n.english
                  ),
                  trailing: DropdownButton<String>(
                    value: language,
                    onChanged: (String? newValue) {
                      if (newValue != null) {
                        ref.read(languageProvider.notifier).setLanguage(newValue);
                      }
                    },
                    items: [
                      DropdownMenuItem(
                        value: 'system',
                        child: Text(l10n.systemLanguage),
                      ),
                      DropdownMenuItem(
                        value: 'en',
                        child: Text(l10n.english),
                      ),
                      DropdownMenuItem(
                        value: 'fr',
                        child: Text(l10n.french),
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: 16),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      l10n.theme,
                      style: Theme.of(context).textTheme.titleSmall,
                    ),
                    const SizedBox(height: 8),
                    SegmentedButton<ThemeMode>(
                      selected: {themeMode},
                      onSelectionChanged: (Set<ThemeMode> newSelection) {
                        ref.read(themeModeProvider.notifier).setThemeMode(newSelection.first);
                      },
                      segments: [
                        ButtonSegment<ThemeMode>(
                          value: ThemeMode.light,
                          label: Text(l10n.themeLight),
                          icon: const Icon(Icons.light_mode),
                        ),
                        ButtonSegment<ThemeMode>(
                          value: ThemeMode.dark,
                          label: Text(l10n.themeDark),
                          icon: const Icon(Icons.dark_mode),
                        ),
                        ButtonSegment<ThemeMode>(
                          value: ThemeMode.system,
                          label: Text(l10n.themeSystem),
                          icon: const Icon(Icons.brightness_auto),
                        ),
                      ],
                    ),
                  ],
                ),
              ],
            ),
          ),
          const Divider(),
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  l10n.about,
                  style: Theme.of(context).textTheme.titleMedium,
                ),
                const SizedBox(height: 16),
                ListTile(
                  title: Text(l10n.appVersion),
                  subtitle: const Text('1.0.0'),
                ),
                ListTile(
                  title: Text(l10n.builtWithFlutter),
                  subtitle: Text(l10n.appDescription),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
