import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../../../core/l10n/app_localizations.dart';
import '../../../providers/app_provider.dart';

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

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final l10n = AppLocalizations.of(context)!;
    final current = ref.watch(localeProvider);
    final cs = Theme.of(context).colorScheme;

    return Scaffold(
      appBar: AppBar(
        title: Text(l10n.language),
        centerTitle: true,
      ),
      body: ListView.separated(
        padding: const EdgeInsets.symmetric(vertical: 8),
        itemCount: supportedLanguages.length,
        separatorBuilder: (_, __) => Divider(
          height: 1,
          indent: 20,
          endIndent: 20,
          color: cs.outline.withAlpha(40),
        ),
        itemBuilder: (context, index) {
          final option = supportedLanguages[index];
          final isSelected = _matches(current, option.locale);
          return ListTile(
            contentPadding:
                const EdgeInsets.symmetric(horizontal: 20, vertical: 4),
            title: Text(
              option.label,
              style: TextStyle(
                fontSize: 15,
                fontWeight:
                    isSelected ? FontWeight.w600 : FontWeight.normal,
                color: isSelected ? cs.primary : cs.onSurface,
              ),
            ),
            trailing: isSelected
                ? Icon(Icons.check_rounded, color: cs.primary, size: 20)
                : null,
            onTap: () {
              ref.read(localeProvider.notifier).setLocale(option.locale);
              Navigator.of(context).pop();
            },
          );
        },
      ),
    );
  }

  bool _matches(Locale a, Locale b) {
    if (a.languageCode != b.languageCode) return false;
    return (a.countryCode ?? '') == (b.countryCode ?? '');
  }
}
