import 'dart:io';
import 'package:file_saver/file_saver.dart';
import 'package:flutter/material.dart';
import 'package:share_plus/share_plus.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:path_provider/path_provider.dart';
import 'package:http/http.dart' as http;
import '../../base/app_loading.dart';
import '../../base/base_screen.dart';
import '../../base/basic_state.dart';
import '../../resources/base_color.dart';
import '../../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();
    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: 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 fileName = 'MyPoint-Cer-$licensePlate.pdf';
  //
  //       await FileSaver.instance.saveFile(
  //         name: fileName,
  //         bytes: bytes,
  //         ext: 'pdf',
  //         mimeType: MimeType.pdf,
  //       );
  //     } else {
  //       print("Tải file thất bại");
  //     }
  //   } catch (e) {
  //     print("Lỗi: $e");
  //   }
  // }

  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.pdf';
        final file = File(filePath);
        await file.writeAsBytes(bytes);
        await Share.shareXFiles([XFile(filePath)], text: 'Giấy chứng nhận cứu hộ');
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('Tải file thất bại')),
        );
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Lỗi: $e')),
      );
    }
  }

  Future<void> _savePdf() async {
    final url = widget.urlDownload;
    final licensePlate = widget.licensePlate;
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('Đang tải PDF...')),
    );
    try {
      final response = await http.get(Uri.parse(url));
      if (response.statusCode == 200) {
        final dir = await getApplicationDocumentsDirectory();
        String baseName = 'MyPoint-Cer-$licensePlate.pdf';
        String path = '${dir.path}/$baseName';
        int count = 0;
        while (File(path).existsSync()) {
          path = '${dir.path}/MyPoint-Cer-$licensePlate-${count++}.pdf';
        }
        final file = File(path);
        await file.writeAsBytes(response.bodyBytes);
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Lưu file thành công:\n${file.path}')),
        );
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('Tải file thất bại')),
        );
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Lỗi: $e')),
      );
    }
  }
}
