import 'package:flutter/material.dart';

import 'package:provider/provider.dart';

import 'package:pshared/provider/locale.dart';

import 'package:pweb/generated/i18n/app_localizations.dart';
import 'package:pweb/services/amplitude.dart';


class LocalePicker extends StatelessWidget {
  final String title;

  const LocalePicker({
    super.key,
    required this.title,
  });

  static const double _pickerWidth = 300;
  static const double _iconSize = 20;
  static const double _gapMedium = 6;
  static const double _gapLarge = 8;

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final loc = AppLocalizations.of(context)!;

    return Consumer<LocaleProvider>(
      builder: (context, localeProvider, _) {
        final currentLocale = localeProvider.locale;
        final options = AppLocalizations.supportedLocales;

        return SizedBox(
          width: _pickerWidth,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Icon(Icons.language_outlined, color: theme.colorScheme.primary, size: _iconSize),
                  const SizedBox(width: _gapMedium),
                  Text(title, style: theme.textTheme.bodyMedium),
                ],
              ),
              const SizedBox(height: _gapLarge),
              DropdownButtonFormField<Locale>(
                initialValue: currentLocale,
                items: options
                    .map(
                      (locale) => DropdownMenuItem(
                        value: locale,
                        child: Text(_localizedLocaleName(locale, loc)),
                      ),
                    )
                    .toList(),
                onChanged: (locale) {
                  if (locale != null) {
                    localeProvider.setLocale(locale);
                    AmplitudeService.localeChanged(locale);
                  }
                },
                decoration: const InputDecoration(
                  border: OutlineInputBorder(),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  String _localizedLocaleName(Locale locale, AppLocalizations loc) {
    switch (locale.languageCode) {
      case 'en':
        return 'English';
      case 'ru':
        return 'Русский';
      case 'de':
        return 'Deutsch';
      default:
        return locale.toString();
    }
  }
}