import 'package:flutter/material.dart';

import 'package:provider/provider.dart';

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


class LocaleChangerDropdown extends StatelessWidget {
  final List<Locale> availableLocales;
  final bool lettersMode;
  const LocaleChangerDropdown({
    super.key,
    required this.availableLocales,
    this.lettersMode = false,
  });

  Widget textLabel(BuildContext context, Locale locale) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: Theme.of(context).primaryColor.withAlpha(26),
        borderRadius: BorderRadius.circular(12),
      ),
      child: Row(
        children: [
          Icon(Icons.language),
          Container(width: 4.0),
          Text(
            locale.languageCode.toUpperCase(),
            style: TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.bold,
              color: Theme.of(context).textTheme.bodyMedium?.color,
            ),
          ),
          Icon(Icons.arrow_drop_down, color: Theme.of(context).iconTheme.color),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    if (availableLocales.length <= 1) {
      // If only one locale is available, do not show the button.
      return const SizedBox.shrink();
    }  

    var localeProvider = Provider.of<LocaleProvider>(context);

    return PopupMenuButton<Locale>(
      icon: lettersMode ? textLabel(context, localeProvider.locale) : getCountryFlag(localeProvider.locale),
      onSelected: localeProvider.setLocale,
      itemBuilder: (BuildContext context) {
        return availableLocales.map((Locale locale) {
          return PopupMenuItem<Locale>(
            value: locale,
            child: lettersMode ? getLocaleNameWidget(locale) : getFlaggedLocale(locale),
          );
        }).toList();
      },
    );
  }
}
