import 'dart:ui';

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

import '../../../core/contracts/auth.dart';
import '../../../providers/home_page_mode_provider.dart';
import '../../../providers/server_provider.dart';
import '../../../providers/session_provider.dart';
import '../../../shared/widgets/auto_dismiss_menu.dart';
import '../../../shared/widgets/server_avatar.dart';

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

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final activeSession = ref.watch(activeSessionProvider);
    final sessionState = ref.watch(sessionProvider);
    final serverList = ref.watch(serverListProvider);
    final mode = ref.watch(homePageModeProvider);

    final isRecommend = mode == HomePageMode.recommend;
    final currentName = isRecommend
        ? '推荐'
        : (activeSession?.serverName ?? '未连接');

    final pausedIds = serverList.maybeWhen(
      data: (list) => {
        for (final s in list)
          if (s.paused) s.id,
      },
      orElse: () => <String>{},
    );
    final sessions = sessionState.maybeWhen(
      data: (data) =>
          data.sessions.where((s) => !pausedIds.contains(s.serverId)).toList(),
      orElse: () => <AuthedSession>[],
    );

    return FPopoverMenu(
      menuBuilder: autoDismissMenuBuilder,
      menuAnchor: Alignment.topLeft,
      childAnchor: Alignment.bottomLeft,
      menu: [FItemGroup(children: [
        FItem(
          prefix: Icon(
            isRecommend ? Icons.radio_button_checked : Icons.radio_button_unchecked,
            size: 20,
            color: isRecommend ? Theme.of(context).colorScheme.primary : null,
          ),
          title: const Row(
            children: [
              Icon(Icons.explore_outlined, size: 20),
              SizedBox(width: 8),
              Text('推荐'),
            ],
          ),
          selected: isRecommend,
          onPress: () {
            ref.read(homePageModeProvider.notifier).state =
                HomePageMode.recommend;
          },
        ),
        for (final s in sessions)
          FItem(
            prefix: Icon(
              !isRecommend && s.serverId == activeSession?.serverId
                  ? Icons.radio_button_checked
                  : Icons.radio_button_unchecked,
              size: 20,
              color: !isRecommend && s.serverId == activeSession?.serverId
                  ? Theme.of(context).colorScheme.primary
                  : null,
            ),
            title: Text(
              s.serverName,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
            selected: !isRecommend && s.serverId == activeSession?.serverId,
            onPress: () {
              ref.read(homePageModeProvider.notifier).state =
                  HomePageMode.server;
              ref.read(sessionProvider.notifier).switchSession(s.serverId);
            },
          ),
      ])],
      builder: (context, controller, child) => GestureDetector(
        onTap: controller.toggle,
        child: child,
      ),
      child: ConstrainedBox(
        constraints: BoxConstraints(
          maxWidth: MediaQuery.sizeOf(context).width - 32,
        ),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(20),
          child: BackdropFilter(
            filter: ImageFilter.blur(sigmaX: 12, sigmaY: 12),
            child: Container(
              padding: const EdgeInsets.fromLTRB(6, 6, 8, 6),
              decoration: BoxDecoration(
                color: Colors.white.withValues(alpha: 0.25),
                borderRadius: BorderRadius.circular(20),
                border: Border.all(color: Colors.white.withValues(alpha: 0.35)),
              ),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  if (isRecommend)
                    Container(
                      width: 28,
                      height: 28,
                      decoration: BoxDecoration(
                        color: Theme.of(
                          context,
                        ).colorScheme.primary.withValues(alpha: 0.15),
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: Icon(
                        Icons.explore_outlined,
                        size: 16,
                        color: Theme.of(context).colorScheme.primary,
                      ),
                    )
                  else
                    ServerAvatar(
                      name: activeSession?.serverName ?? '',
                      iconUrl: '',
                      size: 28,
                      isActive: true,
                    ),
                  const SizedBox(width: 8),
                  Flexible(
                    child: Text(
                      currentName,
                      style: const TextStyle(
                        fontSize: 13,
                        fontWeight: FontWeight.w600,
                        color: Colors.white,
                        shadows: [
                          Shadow(blurRadius: 8, color: Color(0x80000000)),
                        ],
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  const SizedBox(width: 2),
                  const Icon(
                    Icons.arrow_drop_down,
                    size: 18,
                    color: Colors.white,
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
