part of '../space_admin_dialog.dart';

const _kSpaceBannerEvent = 'io.pyramid.space.banner';

Future<void> updatePowerLevelsSafely(
  Room room,
  void Function(Map<String, dynamic> content) mutate,
) async {
  Map<String, dynamic> content;
  try {
    content = Map<String, dynamic>.from(
      await room.client
          .getRoomStateWithKey(room.id, EventTypes.RoomPowerLevels, ''),
    );
  } on MatrixException catch (e) {
    if (e.errcode == 'M_NOT_FOUND') {
      content = <String, dynamic>{};
    } else {
      rethrow;
    }
  }
  final users = content['users'];
  content['users'] =
      users is Map ? Map<String, dynamic>.from(users) : <String, dynamic>{};
  mutate(content);

  // Selbst-Aussperr-Schutz: Nach der Änderung muss der eigene Account immer
  // noch hoch genug stehen, um Power-Levels erneut zu ändern — sonst gäbe es
  // kein Zurück mehr. Greift bei versehentlicher Selbst-Degradierung ODER
  // wenn ein neu geschriebenes Event den eigenen Eintrag nicht enthält.
  final myId = room.client.userID;
  if (myId != null) {
    int asInt(Object? v, int fallback) => v is int ? v : fallback;
    final usersMap = content['users'] as Map<String, dynamic>;
    final myLevel = asInt(usersMap[myId], asInt(content['users_default'], 0));
    final events = content['events'];
    final neededForPl = (events is Map && events['m.room.power_levels'] != null)
        ? asInt(events['m.room.power_levels'], 50)
        : asInt(content['state_default'], 50);
    if (myLevel < neededForPl) {
      throw Exception(
        'Abgebrochen, um eine Selbst-Aussperrung zu verhindern: '
        'Diese Änderung würde dein Level auf $myLevel senken, '
        'aber zum Verwalten der Berechtigungen sind $neededForPl nötig.',
      );
    }
  }

  await room.client
      .setRoomStateWithKey(room.id, EventTypes.RoomPowerLevels, '', content);
}

const _kPowerAdmin = 100;
const _kPowerMod = 50;
const _kPowerMember = 0;

String _powerLabel(int level) {
  if (level >= _kPowerAdmin) return 'Admin';
  if (level >= _kPowerMod) return 'Moderator';
  return 'Mitglied';
}

Color _powerColor(int level, PyramidTheme pt) {
  if (level >= _kPowerAdmin) return const Color(0xFFED4245);
  if (level >= _kPowerMod) return const Color(0xFFF59E0B);
  return pt.fgDim;
}

class SpaceAdminDialog extends ConsumerStatefulWidget {
  final Room space;
  const SpaceAdminDialog({super.key, required this.space});

  @override
  ConsumerState<SpaceAdminDialog> createState() => _SpaceAdminDialogState();
}

class _SpaceAdminDialogState extends ConsumerState<SpaceAdminDialog>
    with SingleTickerProviderStateMixin {
  late TabController _tabs;

  @override
  void initState() {
    super.initState();
    _tabs = TabController(length: 4, vsync: this);
  }

  @override
  void dispose() {
    _tabs.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final pt = PyramidTheme.of(context);
    return Dialog(
      backgroundColor: pt.bg1,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(pt.rLg)),
      insetPadding: const EdgeInsets.symmetric(horizontal: 24, vertical: 40),
      child: ConstrainedBox(
        constraints: const BoxConstraints(maxWidth: 560, maxHeight: 680),
        child: Column(
          children: [
            _DialogHeader(space: widget.space, pt: pt, tabs: _tabs),
            Expanded(
              child: TabBarView(
                controller: _tabs,
                children: [
                  _OverviewTab(space: widget.space),
                  _MembersTab(space: widget.space),
                  _PermissionsTab(space: widget.space),
                  _ChannelsTab(space: widget.space),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _DialogHeader extends ConsumerWidget {
  final Room space;
  final PyramidTheme pt;
  final TabController tabs;
  const _DialogHeader({required this.space, required this.pt, required this.tabs});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final client = ref.watch(matrixClientProvider).valueOrNull;
    final name = space.getLocalizedDisplayname();
    final avatarUri = space.avatar;
    final letter = name.isNotEmpty ? name[0].toUpperCase() : '?';

    Widget avatar;
    if (client != null && avatarUri != null) {
      avatar = MxcAvatar(
        mxcUri: avatarUri,
        client: client,
        size: 40,
        borderRadius: BorderRadius.circular(pt.rBase),
        placeholder: (_) => _InitialAvatar(letter: letter, pt: pt, size: 40),
      );
    } else {
      avatar = _InitialAvatar(letter: letter, pt: pt, size: 40);
    }

    return Container(
      decoration: BoxDecoration(
        border: Border(bottom: BorderSide(color: pt.border)),
      ),
      child: Column(
        children: [
          Padding(
            padding: const EdgeInsets.fromLTRB(20, 20, 12, 12),
            child: Row(
              children: [
                avatar,
                const SizedBox(width: 12),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(name,
                          style: TextStyle(
                              color: pt.fg,
                              fontSize: 17,
                              fontWeight: FontWeight.w700)),
                      Text('Space-Einstellungen',
                          style: TextStyle(color: pt.fgDim, fontSize: 12)),
                    ],
                  ),
                ),
                IconButton(
                  icon: Icon(Icons.close, color: pt.fgDim, size: 20),
                  onPressed: () => Navigator.of(context).pop(),
                ),
              ],
            ),
          ),
          TabBar(
            controller: tabs,
            labelColor: pt.accent,
            unselectedLabelColor: pt.fgDim,
            indicatorColor: pt.accent,
            indicatorSize: TabBarIndicatorSize.label,
            tabs: const [
              Tab(text: 'Übersicht'),
              Tab(text: 'Mitglieder'),
              Tab(text: 'Berechtigungen'),
              Tab(text: 'Kanäle'),
            ],
          ),
        ],
      ),
    );
  }
}
