import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:kasy_kit/core/home_widgets/home_widget_mywidget_service.dart';
import 'package:kasy_kit/core/shared_preferences/shared_preferences.dart';
import 'package:kasy_kit/core/theme/theme.dart';
import 'package:kasy_kit/features/settings/ui/widgets/settings_tile.dart';
import 'package:kasy_kit/i18n/app_locale_display.dart';
import 'package:kasy_kit/i18n/translations.g.dart';

/// Lets the user pick the app locale using endonym labels ([AppLocale.nativeName]).
/// The selection is persisted in SharedPreferences and applied immediately via Slang.
class LanguageSwitcher extends ConsumerWidget {
  const LanguageSwitcher({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final AppLocale current = TranslationProvider.of(context).locale;
    return InkWell(
      onTap: () => _showLanguagePicker(context, ref, current),
      child: Padding(
        padding: const EdgeInsets.symmetric(vertical: KasySpacing.sm),
        child: Row(
          children: <Widget>[
            Icon(KasyIcons.language, size: 21, color: context.colors.onSurface),
            const SizedBox(width: KasySpacing.sm),
            Expanded(
              child: Text(
                context.t.settings.language_title,
                style: context.textTheme.titleMedium?.copyWith(
                  color: context.colors.onSurface,
                ),
              ),
            ),
            Text(
              current.nativeName,
              style: context.textTheme.bodyMedium?.copyWith(
                color: context.colors.muted,
              ),
            ),
            const SizedBox(width: KasySpacing.xs),
            const SettingsListChevron(),
          ],
        ),
      ),
    );
  }

  void _showLanguagePicker(
    BuildContext context,
    WidgetRef ref,
    AppLocale current,
  ) {
    final String sheetTitle = context.t.settings.language_title;
    showModalBottomSheet<void>(
      context: context,
      useRootNavigator: true,
      backgroundColor: context.colors.surface,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(KasyRadius.lg)),
      ),
      builder: (sheetContext) => SafeArea(
        child: Padding(
          padding: const EdgeInsets.fromLTRB(
            KasySpacing.md,
            KasySpacing.sm,
            KasySpacing.md,
            KasySpacing.sm,
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Container(
                width: 36,
                height: 4,
                margin: const EdgeInsets.only(bottom: KasySpacing.md),
                decoration: BoxDecoration(
                  color: sheetContext.colors.onSurface.withValues(alpha: 0.18),
                  borderRadius: BorderRadius.circular(2),
                ),
              ),
              Align(
                alignment: Alignment.centerLeft,
                child: Text(
                  sheetTitle,
                  style: sheetContext.textTheme.titleMedium?.copyWith(
                    fontWeight: FontWeight.w600,
                    color: sheetContext.colors.onSurface,
                  ),
                ),
              ),
              const SizedBox(height: KasySpacing.xs),
              ...AppLocale.values.map((AppLocale locale) {
                final bool isSelected = locale == current;
                return _LocaleOptionTile(
                  locale: locale,
                  isSelected: isSelected,
                  onTap: () {
                    // Close the sheet FIRST. Awaiting work before pop
                    // races with the rebuild triggered by setLocale and
                    // crashed Navigator.pop with !_debugLocked.
                    Navigator.pop(sheetContext);
                    LocaleSettings.setLocale(locale);
                    // Re-render the home widget in the new language —
                    // fire-and-forget so the UI doesn't wait on a
                    // network call (RevenueCat) inside update().
                    unawaited(
                      ref
                          .read(sharedPreferencesProvider)
                          .setAppLocale(locale.languageCode),
                    );
                    unawaited(
                      ref
                          .read(myWidgetHomeWidgetProvider.notifier)
                          .updateForLocale(locale),
                    );
                  },
                );
              }),
            ],
          ),
        ),
      ),
    );
  }
}

class _LocaleOptionTile extends StatelessWidget {
  const _LocaleOptionTile({
    required this.locale,
    required this.isSelected,
    required this.onTap,
  });

  final AppLocale locale;
  final bool isSelected;
  final VoidCallback onTap;

  @override
  Widget build(BuildContext context) {
    final Color primary = context.colors.primary;
    final Color fg = isSelected ? primary : context.colors.onSurface;

    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(KasyRadius.sm),
      child: Padding(
        padding: const EdgeInsets.symmetric(
          horizontal: KasySpacing.xs,
          vertical: KasySpacing.smd,
        ),
        child: Row(
          children: <Widget>[
            Expanded(
              child: Text(
                locale.nativeName,
                style: context.textTheme.bodyLarge?.copyWith(
                  color: fg,
                  fontWeight:
                      isSelected ? FontWeight.w600 : FontWeight.w400,
                ),
              ),
            ),
            if (isSelected)
              Container(
                width: 10,
                height: 10,
                decoration: BoxDecoration(
                  color: primary,
                  shape: BoxShape.circle,
                ),
              ),
          ],
        ),
      ),
    );
  }
}
