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

import 'package:household_keeper/features/tasks/domain/task_sort_option.dart';
import 'package:household_keeper/features/tasks/presentation/sort_preference_notifier.dart';
import 'package:household_keeper/l10n/app_localizations.dart';

/// A reusable sort dropdown widget for use in AppBar actions.
///
/// Displays the current sort option as a labelled button with a sort icon.
/// Tapping opens a popup menu with three options: A–Z, Intervall, Aufwand.
/// The active option is indicated with a visible check mark.
///
/// Reads sort state from [sortPreferenceProvider] and writes via
/// [SortPreferenceNotifier.setSortOption].
class SortDropdown extends ConsumerWidget {
  const SortDropdown({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final current = ref.watch(sortPreferenceProvider);
    final l10n = AppLocalizations.of(context);
    final theme = Theme.of(context);

    return PopupMenuButton<TaskSortOption>(
      onSelected: (value) =>
          ref.read(sortPreferenceProvider.notifier).setSortOption(value),
      itemBuilder: (context) => TaskSortOption.values.map((option) {
        final isSelected = option == current;
        return PopupMenuItem<TaskSortOption>(
          value: option,
          child: Row(
            children: [
              Opacity(
                opacity: isSelected ? 1.0 : 0.0,
                child: const Icon(Icons.check, size: 18),
              ),
              const SizedBox(width: 8),
              Text(_label(option, l10n)),
            ],
          ),
        );
      }).toList(),
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 8),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Icon(Icons.sort),
            const SizedBox(width: 4),
            Text(
              _label(current, l10n),
              style: theme.textTheme.labelLarge,
            ),
          ],
        ),
      ),
    );
  }

  String _label(TaskSortOption option, AppLocalizations l10n) {
    switch (option) {
      case TaskSortOption.alphabetical:
        return l10n.sortAlphabetical;
      case TaskSortOption.interval:
        return l10n.sortInterval;
      case TaskSortOption.effort:
        return l10n.sortEffort;
    }
  }
}
