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

import '../../../core/config/app_config.dart';
import '../../../core/l10n/app_localizations.dart';

/// 七陌 H5 客服 WebView 页面
class CustomerServiceWebView extends StatefulWidget {
  final String userId;
  final String userName;

  const CustomerServiceWebView({
    Key? key,
    required this.userId,
    required this.userName,
  }) : super(key: key);

  @override
  State<CustomerServiceWebView> createState() => _CustomerServiceWebViewState();
}

class _CustomerServiceWebViewState extends State<CustomerServiceWebView> {
  late WebViewController _webViewController;

  @override
  void initState() {
    super.initState();
    _initializeWebViewController();
  }

  void _initializeWebViewController() {
    _webViewController = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..addJavaScriptChannel(
        'flutterChannel',
        onMessageReceived: (JavaScriptMessage message) {
          _handleJavaScriptMessage(message.message);
        },
      )
      ..setNavigationDelegate(
        NavigationDelegate(
          onPageFinished: (_) {
            // 页面加载完成，注入JS接口
            _injectJavaScriptInterface();
          },
        ),
      )
      // 加载部署在自有服务器上的 HTML，通过 URL 参数传递用户信息
      // 该 HTML 处理七陌 SDK 初始化，避免跨域问题
      ..loadRequest(
        Uri.parse(
          '${AppConfig.customerServiceHost}${AppConfig.customerServiceChatPath}'
          '?userId=${Uri.encodeComponent(widget.userId)}'
          '&userName=${Uri.encodeComponent(widget.userName)}',
        ),
      );
  }

  /// 注入JavaScript接口供HTML调用
  void _injectJavaScriptInterface() {
    _webViewController.runJavaScript(
      '''
      window.flutterChannel = {
        postMessage: function(message) {
          flutterChannel.postMessage(message);
        }
      };
      '''
    );
  }

  /// 处理来自JavaScript的消息
  void _handleJavaScriptMessage(String message) {
    if (message == 'close' && mounted) {
      Navigator.of(context).pop();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: const BorderRadius.only(
          topLeft: Radius.circular(16),
          topRight: Radius.circular(16),
        ),
      ),
      child: Column(
        children: [
          // 顶部栏：退出按钮（左）+ 拖拽指示条（中）
          SizedBox(
            height: 48,
            width: double.infinity,
            child: Stack(
              children: [
                // 拖拽指示条居中
                Center(
                  child: Container(
                    width: 36,
                    height: 4,
                    decoration: BoxDecoration(
                      color: Colors.grey.withAlpha(80),
                      borderRadius: BorderRadius.circular(2),
                    ),
                  ),
                ),
                // 退出按钮左对齐
                Align(
                  alignment: Alignment.centerLeft,
                  child: TextButton(
                    onPressed: () => Navigator.of(context).pop(),
                    child: Text(
                      AppLocalizations.of(context)!.customerServiceLeave,
                      style: const TextStyle(color: Colors.grey, fontSize: 15),
                    ),
                  ),
                ),
              ],
            ),
          ),
          // WebView 内容区
          Expanded(
            child: WebViewWidget(controller: _webViewController),
          ),
        ],
      ),
    );
  }
}
