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

import '../../../state/app/modules/app_modules.dart';
import '../../../state/app/modules/settings/bloc/settings_cubit.dart';
import '../../../storage/settings.dart' as model;
import '../../../utils/haptics.dart';
import '../../../widget/confirm_dialog.dart';
import 'data/default_settings.dart';

/// Reorderable list with bottom-bar slot configuration on top.
///
/// Used both inline in the "Mehr" edit mode and as the body of
/// [ModulesSettingsPage] from the main settings.
class ModuleSortBody extends StatelessWidget {
  const ModuleSortBody({super.key});

  @override
  Widget build(
    BuildContext context,
  ) => BlocBuilder<SettingsCubit, model.Settings>(
    builder: (context, _) {
      final settings = context.read<SettingsCubit>();
      final modulesSettings = settings.val().modulesSettings;

      void changeVisibility(Modules module) {
        Haptics.selection();
        var hidden = settings.val(write: true).modulesSettings.hiddenModules;
        if (hidden.contains(module)) {
          hidden.remove(module);
        } else if (hidden.length < 3) {
          hidden.add(module);
        }
      }

      return ReorderableListView(
        header: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            const Padding(
              padding: EdgeInsets.symmetric(horizontal: 16, vertical: 16),
              child: Text(
                'Halte und ziehe einen Eintrag, um ihn zu verschieben.\nEs können 3 Bereiche ausgeblendet werden.',
                textAlign: TextAlign.center,
              ),
            ),
            SwitchListTile(
              title: const Text('Modulleiste automatisch füllen'),
              subtitle: const Text(
                'Auf größeren Bildschirmen werden mehr Module direkt angezeigt',
              ),
              value: modulesSettings.autoFillBottomBar,
              onChanged: (value) {
                Haptics.selection();
                settings.val(write: true).modulesSettings.autoFillBottomBar =
                    value;
              },
            ),
            if (!modulesSettings.autoFillBottomBar)
              ListTile(
                title: const Text('Anzahl Slots in der Modulleiste'),
                subtitle: Text(
                  '${modulesSettings.fixedBottomBarSlots} Module (zzgl. „Mehr")',
                ),
                trailing: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    IconButton(
                      tooltip: 'Slot entfernen',
                      icon: const Icon(Icons.remove_circle_outline),
                      onPressed:
                          modulesSettings.fixedBottomBarSlots >
                              AppModule.minBottomBarSlots
                          ? () =>
                                settings
                                        .val(write: true)
                                        .modulesSettings
                                        .fixedBottomBarSlots -=
                                    1
                          : null,
                    ),
                    Text('${modulesSettings.fixedBottomBarSlots}'),
                    IconButton(
                      tooltip: 'Slot hinzufügen',
                      icon: const Icon(Icons.add_circle_outline),
                      onPressed:
                          modulesSettings.fixedBottomBarSlots <
                              AppModule.maxBottomBarSlots
                          ? () =>
                                settings
                                        .val(write: true)
                                        .modulesSettings
                                        .fixedBottomBarSlots +=
                                    1
                          : null,
                    ),
                  ],
                ),
              ),
            const Divider(),
          ],
        ),
        children: AppModule.modules(context, showFiltered: true)
            .map(
              (key, value) => MapEntry(
                key,
                value.toListTile(
                  context,
                  key: Key(key.name),
                  isReorder: true,
                  onVisibleChange: () => changeVisibility(key),
                  isVisible: !settings
                      .val()
                      .modulesSettings
                      .hiddenModules
                      .contains(key),
                ),
              ),
            )
            .values
            .toList(),
        onReorderItem: (oldIndex, newIndex) {
          final displayed = AppModule.modules(
            context,
            showFiltered: true,
          ).keys.toList();
          settings.val(write: true).modulesSettings.moduleOrder =
              AppModule.reorderModuleOrder(
                displayed: displayed,
                effective: AppModule.effectiveModuleOrder(
                  settings.val().modulesSettings,
                ),
                oldIndex: oldIndex,
                newIndex: newIndex,
              );
        },
      );
    },
  );
}

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

  @override
  Widget build(BuildContext context) =>
      BlocBuilder<SettingsCubit, model.Settings>(
        builder: (context, _) {
          final settings = context.read<SettingsCubit>();
          final isModified =
              settings.val().modulesSettings.toJson().toString() !=
              DefaultSettings.get().modulesSettings.toJson().toString();
          return Scaffold(
            appBar: AppBar(
              title: const Text('Module'),
              actions: [
                IconButton(
                  tooltip: 'Auf Standard zurücksetzen',
                  onPressed: isModified
                      ? () => ConfirmDialog(
                          title: 'Module zurücksetzen?',
                          content:
                              'Reihenfolge, sichtbare Module und die '
                              'Konfiguration der Bottom-Bar werden auf die '
                              'Standardwerte zurückgesetzt.',
                          confirmButton: 'Zurücksetzen',
                          onConfirm: () =>
                              settings.val(write: true).modulesSettings =
                                  DefaultSettings.get().modulesSettings,
                        ).asDialog(context)
                      : null,
                  icon: const Icon(Icons.undo_outlined),
                ),
              ],
            ),
            body: const ModuleSortBody(),
          );
        },
      );
}
