import 'package:flutter/material.dart';

import 'package:provider/provider.dart';

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

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


class LocalePicker extends StatelessWidget {
  const LocalePicker({super.key});

  static const double _pickerWidth = 300;

  @override
  Widget build(BuildContext 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: 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);
              }
            },
            decoration: const InputDecoration(border: OutlineInputBorder()),
          ),
        );
      },
    );
  }

  String _localizedLocaleName(Locale locale, AppLocalizations loc) {
    switch (locale.languageCode) {
      case 'en':
        return loc.englishLanguage;
      case 'ru':
        return loc.russianLanguage;
      case 'de':
        return loc.germanLanguage;
      default:
        return locale.toString();
    }
  }
}
