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

class DaciaLoginWebView extends StatefulWidget {
  final Function(String) onTokenExtracted;
  final Function(String) onError;

  const DaciaLoginWebView({
    super.key,
    required this.onTokenExtracted,
    required this.onError,
  });

  @override
  State<DaciaLoginWebView> createState() => _DaciaLoginWebViewState();
}

class _DaciaLoginWebViewState extends State<DaciaLoginWebView> {
  late final WebViewController _controller;

  @override
  void initState() {
    super.initState();
    _controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..enableZoom(false)
      ..setNavigationDelegate(
        NavigationDelegate(
          onPageFinished: (url) async {
            print("🔄 Geladene URL: $url");

            final uri = Uri.parse(url);
            final token = uri.queryParameters['gig_ssoToken'];

            if (token != null && mounted) {
              print("✅ Erfolgreicher Token: $token");
              widget.onTokenExtracted(token);
              Navigator.pop(context);
            } else {
              print("❌ Kein Token in der URL gefunden");
            }
          },
          onWebResourceError: (error) {
            if (mounted) widget.onError("WebView-Fehler: ${error.description}");
          },
        ),
      )
      ..loadRequest(Uri.parse('https://my.dacia.de'));
  }

  Future<String> _extractTokenFromWebView() async {
    try {
      final token = await _controller.runJavaScriptReturningResult('''
        localStorage.getItem('gig_ssoToken') || 
        document.querySelector('input[name="gig_ssoToken"]')?.value
      ''');
      print("Token2");
      print(token);
      return token.toString();
    } catch (e) {
      print("Fehler bei der Extraktion: $e");
      return '';
    }
  }

  @override
  Widget build(BuildContext context) {
    return WebViewWidget(controller: _controller);
  }
}

Future<bool> checkDaciaLogin(BuildContext context) async {
  try {
    String? extractedToken;

    await showDialog(
      context: context,
      builder: (context) => AlertDialog(
        content: SizedBox(
          width: MediaQuery.of(context).size.width * 0.9,
          height: MediaQuery.of(context).size.height * 0.7,
          child: DaciaLoginWebView(
            onTokenExtracted: (token) => extractedToken = token,
            onError: (error) => print(error),
          ),
        ),
      ),
    );

    return extractedToken != null;
  } catch (e) {
    print('Fehler: $e');
    return false;
  }
}