import 'package:flutter/material.dart';
import 'package:qhd_prevention/customWidget/custom_button.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:qhd_prevention/customWidget/toast_util.dart';

/// 可复用的地图 WebView 组件
/// BaiduMapWebView(
///   controller: _controller,
///   isLoading: _isLoading,
///   errorMessage: _errorMessage,
///   onRetry: _initLocation,
/// )
/// ```
class BaiduMapWebView extends StatelessWidget {
  final WebViewController? controller;
  final bool isLoading;
  final String? errorMessage;
  final VoidCallback onRetry;

  const BaiduMapWebView({
    super.key,
    required this.controller,
    required this.isLoading,
    required this.errorMessage,
    required this.onRetry,
  });

  @override
  Widget build(BuildContext context) {
    if (errorMessage != null) {
      return Center(
        child: Padding(
          padding: const EdgeInsets.all(20.0),
          child: Column(mainAxisSize: MainAxisSize.min, children: [
            const Icon(Icons.error_outline, color: Colors.red, size: 50),
            const SizedBox(height: 16),
            Text(
              errorMessage!,
              textAlign: TextAlign.center,
              style: const TextStyle(fontSize: 16),
            ),
            const SizedBox(height: 24),
            CustomButton(text: '重试', backgroundColor: Colors.blue, onPressed: onRetry)
          ]),
        ),
      );
    }

    if (isLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    // 非加载且无错误时，controller 应该存在；若为空则显示提示
    if (controller == null) {
      return Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Icon(Icons.map_outlined, size: 48),
            const SizedBox(height: 8),
            const Text('地图未初始化'),
            const SizedBox(height: 12),
            ElevatedButton(onPressed: onRetry, child: const Text('重试初始化')),
          ],
        ),
      );
    }

    return WebViewWidget(controller: controller!);
  }
}
