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

import '../core/config/app_config.dart';
import '../core/l10n/app_localizations.dart';
import '../data/repositories/auth_repository.dart';
import '../presentation/screens/customer_service/customer_service_webview.dart';
import 'auth_provider.dart';
import 'profile_provider.dart';

/// 打开客服聊天（H5 WebView 方式），未登录时跳转登录页
Future<void> openCustomerService(BuildContext context, WidgetRef ref) async {
  if (!AppConfig.customerServiceEnabled) {
    return;
  }

  final isLoggedIn = ref.read(isLoggedInProvider);
  if (!isLoggedIn) {
    context.push('/login');
    return;
  }

  // 提前读取 l10n，避免跨异步使用 BuildContext
  final l10n = AppLocalizations.of(context)!;

  // 等待 profile 加载完成，避免用占位 uid 打开客服
  var profileState = ref.read(profileProvider);
  if (profileState.isLoadingProfile) {
    int waited = 0;
    while (ref.read(profileProvider).isLoadingProfile && waited < 30) {
      await Future.delayed(const Duration(milliseconds: 100));
      waited++;
    }
    profileState = ref.read(profileProvider);
  }

  final profile = profileState.user;
  final userName = profile.rawEmail.isNotEmpty ? profile.rawEmail : l10n.user;

  // uid 优先用 profile，为空时从登录时写入的 secure storage 兜底
  String userId = profile.uid;
  if (userId.isEmpty) {
    userId = await ref.read(authRepositoryProvider).getSavedUid() ?? '';
  }

  if (!context.mounted) return;

  // 以 Modal BottomSheet 形式展示七陌 H5 客服
  showModalBottomSheet<void>(
    context: context,
    useRootNavigator: true,
    isScrollControlled: true,
    enableDrag: false,
    backgroundColor: Colors.transparent,
    barrierColor: Colors.black.withAlpha(102), // 50% 透明度
    builder: (BuildContext bottomSheetContext) {
      return SizedBox(
        height: MediaQuery.of(bottomSheetContext).size.height * 0.85,
        child: CustomerServiceWebView(
          userId: userId,
          userName: userName,
        ),
      );
    },
  );
}
