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;
  WebViewController? _controller; // Nullable cho web platform
  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;
    }
    
    // Web platform: mở URL trong tab mới và đóng màn hình ngay
    if (kIsWeb) {
      AppLoading().hide();
      Future.microtask(() async {
        await _openUrlInBrowser();
        if (mounted) {
          if (Navigator.of(context).canPop()) {
            Navigator.of(context).pop();
          }
        }
      });
      return;
    }
    
    // Mobile platform: khởi tạo WebView
    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() {
    // Web platform: không hiển thị màn hình trung gian (đã auto mở tab mới ở initState)
    if (kIsWeb) {
      return const SizedBox.shrink();
    }
    
    // Mobile platform: sử dụng WebView
    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 {
    if (kIsWeb) return; // Web không cần clear cookies
    final cookieManager = WebViewCookieManager();
    await cookieManager.clearCookies();
  }

  void _handleBack() async {
    if (kIsWeb) {
      // Web: chỉ đơn giản quay lại
      if (context.mounted) Navigator.of(context).pop();
      return;
    }
    
    // Mobile: kiểm tra WebView có thể go back không
    if (_controller != null && await _controller!.canGoBack()) {
      _controller!.goBack();
    } else {
      if (context.mounted) Navigator.of(context).pop();
    }
  }

  Future<void> _openUrlInBrowser() async {
    try {
      final uri = Uri.parse(formatUrl(input.url));
      if (await canLaunchUrl(uri)) {
        await launchUrl(uri, mode: LaunchMode.externalApplication);
      } else {
        if (kDebugMode) {
          print('Could not launch URL: ${input.url}');
        }
      }
    } catch (e) {
      if (kDebugMode) {
        print('Error launching URL: $e');
      }
    }
  }

  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://')) {
      openStringUrlExternally(url);
      return NavigationDecision.prevent;
    }
    if (url.startsWith('sms:')) {
      final uri = Uri.parse(url);
      launchUrl(uri);
      return NavigationDecision.prevent;
    }
    return NavigationDecision.navigate;
  }

  // Widget _buildWebViewForWeb() {
  //   if (!kIsWeb) return const SizedBox.shrink();
  //
  //   return Container(
  //     width: double.infinity,
  //     height: double.infinity,
  //     child: Column(
  //       children: [
  //         // Header với URL
  //         Container(
  //           padding: const EdgeInsets.all(16),
  //           color: Colors.grey[100],
  //           child: Row(
  //             children: [
  //               Icon(Icons.language, color: Colors.blue),
  //               const SizedBox(width: 8),
  //               Expanded(
  //                 child: Text(
  //                   input.url,
  //                   style: const TextStyle(fontSize: 14),
  //                   overflow: TextOverflow.ellipsis,
  //                 ),
  //               ),
  //               const SizedBox(width: 8),
  //               ElevatedButton.icon(
  //                 onPressed: () => _openUrlInBrowser(),
  //                 icon: const Icon(Icons.open_in_new, size: 16),
  //                 label: const Text('Mở tab mới'),
  //                 style: ElevatedButton.styleFrom(
  //                   padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
  //                 ),
  //               ),
  //             ],
  //           ),
  //         ),
  //         // iframe area
  //         Expanded(
  //           child: Container(
  //             width: double.infinity,
  //             height: double.infinity,
  //             decoration: BoxDecoration(
  //               border: Border.all(color: Colors.grey[300]!),
  //             ),
  //             child: Center(
  //               child: Column(
  //                 mainAxisAlignment: MainAxisAlignment.center,
  //                 children: [
  //                   Icon(Icons.web, size: 64, color: Colors.grey[400]),
  //                   const SizedBox(height: 16),
  //                   Text(
  //                     'WebView không hỗ trợ trực tiếp trên web',
  //                     style: Theme.of(context).textTheme.headlineSmall?.copyWith(
  //                       color: Colors.grey[600],
  //                     ),
  //                     textAlign: TextAlign.center,
  //                   ),
  //                   const SizedBox(height: 8),
  //                   Text(
  //                     'Vui lòng click "Mở tab mới" để xem nội dung',
  //                     style: Theme.of(context).textTheme.bodyMedium?.copyWith(
  //                       color: Colors.grey[500],
  //                     ),
  //                     textAlign: TextAlign.center,
  //                   ),
  //                   const SizedBox(height: 24),
  //                   ElevatedButton.icon(
  //                     onPressed: () => _openUrlInBrowser(),
  //                     icon: const Icon(Icons.open_in_new),
  //                     label: const Text('Mở trong tab mới'),
  //                     style: ElevatedButton.styleFrom(
  //                       padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
  //                     ),
  //                   ),
  //                 ],
  //               ),
  //             ),
  //           ),
  //         ),
  //       ],
  //     ),
  //   );
  // }
}
