import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/widgets/back_button.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:webview_flutter/webview_flutter.dart';
import '../../base/app_loading.dart';
import '../../base/base_screen.dart';
import '../../base/basic_state.dart';
import '../../directional/directional_screen.dart';
import '../../widgets/custom_navigation_bar.dart';

class BaseWebViewInput {
  final String? title;
  final String url;
  final bool isFullScreen;

  const BaseWebViewInput({this.title, required this.url, this.isFullScreen = false});
}

class BaseWebViewScreen extends BaseScreen {
  const BaseWebViewScreen({super.key});

  @override
  State<BaseWebViewScreen> createState() => _BaseWebViewScreenState();
}

class _BaseWebViewScreenState extends BaseState<BaseWebViewScreen> with BasicState {
  late final BaseWebViewInput input;
  late final WebViewController _controller;
  String? _dynamicTitle;

  @override
  void initState() {
    super.initState();
    final args = Get.arguments;
    if (args is BaseWebViewInput && args.url.isNotEmpty) {
      input = args;
    } else {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        Get.back();
      });
      return;
    }
    AppLoading().show();
    _controller =
        WebViewController()
          ..setJavaScriptMode(JavaScriptMode.unrestricted)
          ..setBackgroundColor(Colors.transparent)
          ..setNavigationDelegate(
            NavigationDelegate(
              onPageFinished: (_) async {
                AppLoading().hide();
                final title = await _controller.getTitle();
                setState(() {
                  _dynamicTitle = title;
                });
              },
              onWebResourceError: (error) {
                AppLoading().hide();
                if (error.description != 'about:blank') {
                  if (kDebugMode) {
                    print('WebView error: ${error.description}');
                  }
                  // Có thể hiển thị lỗi nếu cần
                  // showAlertError(content: error.description);
                }
              },
              onNavigationRequest: _handleNavigation,
            ),
          )
          ..loadRequest(Uri.parse(formatUrl(input.url)));
    _clearCookies();
  }

  String formatUrl(String inputUrl) {
    if (inputUrl.isEmpty) return '';
    
    try {
      if (!inputUrl.startsWith('http://') && !inputUrl.startsWith('https://')) {
        return 'https://$inputUrl';
      }
      return inputUrl;
    } catch (e) {
      if (kDebugMode) {
        print('Failed to format URL: $inputUrl - $e');
      }
      return inputUrl;
    }
  }

  @override
  Widget createBody() {
    return Scaffold(
      appBar:
          input.isFullScreen
              ? null
              : CustomNavigationBar(
                  title: input.title ?? _dynamicTitle ?? Uri.parse(input.url).host,
                  leftButtons: [
                    CustomBackButton(onPressed: _handleBack),
                  ],
                ),
      body: Stack(
        children: [
          SafeArea(
            child: WebViewWidget(
              controller: _controller,
              gestureRecognizers: const <Factory<OneSequenceGestureRecognizer>>{
                Factory<VerticalDragGestureRecognizer>(VerticalDragGestureRecognizer.new),
              },
            ),
          ),
          if (input.isFullScreen)
            Positioned(top: MediaQuery.of(context).padding.top + 8, left: 8, child: CustomBackButton()),
        ],
      ),
    );
  }

  Future<void> _clearCookies() async {
    final cookieManager = WebViewCookieManager();
    await cookieManager.clearCookies();
  }

  void _handleBack() async {
    if (await _controller.canGoBack()) {
      _controller.goBack();
    } else {
      if (context.mounted) Navigator.of(context).pop();
    }
  }

  NavigationDecision _handleNavigation(NavigationRequest request) {
    final url = request.url;
    debugPrint("➡️ Navigating: $url");
    if (url.isEmpty || url == 'about:blank') {
      return NavigationDecision.prevent;
    }
    if (url.startsWith('itms-apps://')) {
      openAppStore(url);
      return NavigationDecision.prevent;
    }
    if (url.startsWith('sms:')) {
      final uri = Uri.parse(url);
      launchUrl(uri);
      return NavigationDecision.prevent;
    }
    return NavigationDecision.navigate;
  }
}
