import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'dart:ui' as ui;

import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:initial_folder/base_service.dart';
import 'package:initial_folder/helper/user_info.dart';
import 'package:initial_folder/models/certificate_model.dart';
import 'package:initial_folder/models/check_certificate.model.dart';
import 'package:initial_folder/models/my_certificate.dart';
import 'package:path_provider/path_provider.dart';
import 'package:pdf/widgets.dart' as pw;
import 'package:pdf/pdf.dart';

class AllCertificateServices {
  Future<Map<String, dynamic>> uploadCertificate(
      String idPayment, File pdfFile) async {
    String? token = await UsersInfo().getToken();

    try {
      Uri url = Uri.parse("$baseUrl/users/upload-sertifikat/$idPayment");

      var request = http.MultipartRequest('POST', url);

      request.headers.addAll(headerWithToken(token));
      request.files
          .add(await http.MultipartFile.fromPath('file', pdfFile.path));

      var response = await request.send();
      var responseData = await response.stream.bytesToString();
      var jsonData = json.decode(responseData);

      if (response.statusCode == 200) {
        throw ("Sertifikat berhasil di unduh");
      } else {
        throw Exception('Gagal mengunggah sertifikat: ${jsonData['message']}');
      }
    } catch (e) {
      return {'status': 500, 'error': true, 'message': e.toString()};
    }
  }

  Future getAllCertificate() async {
    int? idUser = await UsersInfo().getIdUser();
    String? token = await UsersInfo().getToken();

    Uri url = Uri.parse("$baseUrl/homepage/get_all_sertifikat/$idUser");

    var response = await http.get(url, headers: headerWithToken(token!));

    if (response.statusCode == 200) {
      var data = jsonDecode(response.body)['data'][0];
      List<DataMyCertificateModel> certif = [];

      for (var item in data) {
        certif.add(DataMyCertificateModel.fromJson(item));
      }

      return certif;
    } else {
      throw Exception('Data Kursus Teratas Gagal Diambil');
    }
  }

  Future getSertif(String idCourse) async {
    int? idUser = await UsersInfo().getIdUser();
    String? token = await UsersInfo().getToken();

    Uri url =
        Uri.parse("$baseUrl/homepage/sertifikat/$idUser?course_id=$idCourse");
    var response = await http.get(url, headers: headerWithToken(token!));

    if (response.statusCode == 200) {
      var data = jsonDecode(response.body)['data'];
      List<CertificateModel> certif = [];

      for (var item in data) {
        certif.add(CertificateModel.fromJson(item));
      }

      print("ini data sertif dari api :  ${response.body}");

      return certif;
    } else {
      throw Exception('Data Kursus Teratas Gagal Diambil');
    }
  }

  Future checkSertif(String text) async {
    print("Ini sertif ${text}");
    Uri url = Uri.parse("$baseUrl/homepage/cek_status_sertifikat/$text");
    var response = await http.get(url);
    var data = jsonDecode(response.body);

    if (data['status'] == 200) {
      if (data != null && data['data'] != null && data['data'].length > 0) {
        var certifData = data['data'][0];
        CheckCertificateData certif = CheckCertificateData.fromJson(certifData);
        print("Berhasil cek sertif ${response.body}");
        return certif;
      } else {
        print("Kosong cek sertif ${response.body}");
        return null;
      }
    } else if (data['status'] == 404) {
      print("Gagal cek sertif ${response.body}");
      return data['massages'] != null
          ? data['massages']
          : "Error message not available";
    }
  }

  Future searchCertif(String keyword) async {
    int? idUser = await UsersInfo().getIdUser();
    String? token = await UsersInfo().getToken();

    Uri url = Uri.parse(
        "$baseUrl/homepage/search_sertifikat/$idUser?keyword=$keyword");

    var response = await http.get(url, headers: headerWithToken(token!));

    List<DataMyCertificateModel> certif = [];

    if (response.statusCode == 200) {
      var data = jsonDecode(response.body)['data'][0];

      for (var item in data) {
        certif.add(DataMyCertificateModel.fromJson(item));
      }

      return certif;
    } else if (response.statusCode == 400) {
      return certif;
    } else {
      return certif;
    }
  }

Future<void> convertAndUpload(GlobalKey _globalKey, String idPayment) async {
  try {
    RenderRepaintBoundary boundaryRenderObject =
        _globalKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
    ui.Image image = await boundaryRenderObject.toImage(pixelRatio: 3.0);
    ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);
    Uint8List pngBytes = byteData!.buffer.asUint8List();

    final pdf = pw.Document();
    
    final pdfPageFormat = PdfPageFormat.a4.landscape.copyWith(
      marginBottom: 0,
      marginTop: 0,
      marginLeft: 0,
      marginRight: 0,
    );

    pdf.addPage(
      pw.Page(
        pageFormat: pdfPageFormat,
        build: (pw.Context context) {
          return pw.Center(
            child: pw.Image(pw.MemoryImage(pngBytes),
              fit: pw.BoxFit.cover, ),
          );
        },
      ),
    );

    Directory tempDir = await getTemporaryDirectory();
    String tempPath = '${tempDir.path}/certificate_${idPayment}.pdf';
    File tempFile = File(tempPath);
    
    await tempFile.writeAsBytes(await pdf.save());

    await uploadCertificate(idPayment, tempFile);
  } catch (e) {
    throw Exception('Gagal mengonversi PNG ke PDF: $e');
  }
}

}
