import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:mypoint_flutter_app/shared/widgets/custom_toast_message.dart';
import 'package:share_plus/share_plus.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:path_provider/path_provider.dart';
import 'package:http/http.dart' as http;
import '../../shared/widgets/loading/app_loading.dart';
import '../../shared/widgets/base_view/base_screen.dart';
import '../../shared/widgets/base_view/basic_state.dart';
import '../../core/theme/base_color.dart';
import '../../shared/widgets/custom_navigation_bar.dart';
import 'dart:typed_data' as typed_data;

class TrafficServiceCertificateScreen extends BaseScreen {
  final String urlView;
  final String urlDownload;
  final String licensePlate;

  const TrafficServiceCertificateScreen({
    super.key,
    required this.urlView,
    required this.urlDownload,
    required this.licensePlate,
  });

  @override
  State<TrafficServiceCertificateScreen> createState() => _TrafficServiceCertificateScreenState();
}

class _TrafficServiceCertificateScreenState extends BaseState<TrafficServiceCertificateScreen> with BasicState {
  late final WebViewController _controller;

  @override
  void initState() {
    super.initState();
    if (kIsWeb) {
      _openUrlInBrowser();
    } else {
      _initializeWebView();
    }
  }

  Future<void> _openUrlInBrowser() async {
    Future.microtask(() async {
      final uri = Uri.parse(widget.urlView);
      if (await canLaunchUrl(uri)) {
        await launchUrl(uri, mode: LaunchMode.externalApplication);
      } else if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('Không thể mở giấy chứng nhận')),
        );
      }
    });
  }

  void _initializeWebView() {
    AppLoading().show();
    _controller = WebViewController()
      ..loadRequest(Uri.parse(widget.urlView))
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setNavigationDelegate(
        NavigationDelegate(
          onPageFinished: (_) async {
            AppLoading().hide();
          },
          onWebResourceError: (error) {
            AppLoading().hide();
          },
        ),
      );
  }

  @override
  Widget createBody() {
    return Scaffold(
      appBar: CustomNavigationBar(title: "Giấy chứng nhận cứu hộ VNTRA"),
      body: kIsWeb ? _WebFallback(onRetry: _openUrlInBrowser) : WebViewWidget(controller: _controller),
      bottomNavigationBar: _buildBottomButtonEditMode(),
    );
  }

  Widget _buildBottomButtonEditMode() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
      decoration: const BoxDecoration(
        color: Colors.white,
        boxShadow: [BoxShadow(color: Colors.black54, blurRadius: 8, offset: Offset(0, 4))],
      ),
      child: SafeArea(
        top: false,
        child: SizedBox(
          width: double.infinity,
          height: 48,
          child: ElevatedButton(
            onPressed: _savePdfToFiles,
            style: ElevatedButton.styleFrom(
              backgroundColor: BaseColor.primary500,
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
            ),
            child: const Text(
              'Lưu file',
              style: TextStyle(fontSize: 18, color: Colors.white, fontWeight: FontWeight.bold),
            ),
          ),
        ),
      ),
    );
  }

  Future<void> _savePdfToFiles() async {
    final url = widget.urlDownload;
    final licensePlate = widget.licensePlate;
    try {
      final response = await http.get(Uri.parse(url));
      if (response.statusCode == 200) {
        typed_data.Uint8List bytes = response.bodyBytes;
        final dir = await getTemporaryDirectory();
        final filePath = '${dir.path}/MyPoint-Cer-$licensePlate-${DateTime.now().toString()}.pdf';
        final file = File(filePath);
        await file.writeAsBytes(bytes);
        await Share.shareXFiles([XFile(filePath)], text: 'Giấy chứng nhận cứu hộ');
        showToastMessage('Lưu file thành công');
      } else {
        showToastMessage('Tải file thất bại');
      }
    } catch (e) {
      showToastMessage('Tải file thất bại');
    }
  }
}

class _WebFallback extends StatelessWidget {
  final VoidCallback onRetry;

  const _WebFallback({required this.onRetry});

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          const Padding(
            padding: EdgeInsets.symmetric(horizontal: 24.0),
            child: Text(
              'Giấy chứng nhận đang được mở trong tab trình duyệt mới. '
                  'Nếu không tự mở, vui lòng chọn "Mở lại" hoặc sử dụng nút Lưu file.',
              textAlign: TextAlign.center,
            ),
          ),
          const SizedBox(height: 16),
          ElevatedButton(
            onPressed: onRetry,
            child: const Text('Mở lại'),
          ),
        ],
      ),
    );
  }
}