import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:webview_flutter/webview_flutter.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 StatefulWidget {
  const BaseWebViewScreen({super.key});

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

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

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

    final args = Get.arguments;
    if (args is BaseWebViewInput) {
      input = args;
    } else {
      throw Exception('BaseWebViewInput is required in arguments');
    }

    _controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setNavigationDelegate(
        NavigationDelegate(
          onPageFinished: (_) async {
            final title = await _controller.getTitle();
            setState(() {
              _dynamicTitle = title;
            });
          },
          onWebResourceError: (_) {
            _showWebErrorDialog();
          },
        ),
      )
      ..loadRequest(Uri.parse(input.url));

    _clearCookies();
  }

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

  void _showWebErrorDialog() {
    showDialog(
      context: context,
      builder: (_) => AlertDialog(
        title: const Text("Lỗi"),
        content: const Text("Không thể tải nội dung. Vui lòng thử lại sau."),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text("Đóng"),
          )
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: input.isFullScreen
          ? null
          : AppBar(
        title: Text(
          input.title ?? _dynamicTitle ?? Uri.parse(input.url).host,
          style: const TextStyle(fontSize: 16),
        ),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: _handleBack,
        ),
      ),
      body: SafeArea(
        child: WebViewWidget(controller: _controller),
      ),
    );
  }

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