import 'dart:convert';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:internet_connection_checker/internet_connection_checker.dart';
import 'package:intl/intl.dart';
import '../../../connection/connection.dart';
import '../../../migrations/databasehelper.dart';
import '../../../models/asset_status_model.dart';
import 'package:http/http.dart' as http;

class SyncronizationPeminjamanData {
  Future<int> addData(AssetStatusModel assetStatusModel) async {
    final dbClient = await conn.db;
    late int result;
    try {
      result = await dbClient!.insert(
          SqfliteDatabaseHelper.peminjamanTable, assetStatusModel.toJson());
    } catch (e) {
      print('Error adding data to local SQLite: $e');
      result = 0; // Handle the error appropriately
    }
    return result;
  }

  Future<List> fetchData() async {
    var dbclient = await conn.db;
    List assetStatusList = [];
    try {
      List<Map<String, dynamic>> maps = await dbclient!
          .query(SqfliteDatabaseHelper.peminjamanTable, orderBy: 'id DESC');
      for (var item in maps) {
        assetStatusList.add(item);
      }
    } catch (e) {
      print(e.toString());
    }
    return assetStatusList;
  }

  static Future<bool> isInternet() async {
    var connectivityResult = await (Connectivity().checkConnectivity());
    if (connectivityResult == ConnectivityResult.mobile) {
      if (await InternetConnectionChecker().hasConnection) {
        print("Mobile data detected & internet connection confirmed.");
        return true;
      } else {
        print('No internet :( Reason:');
        return false;
      }
    } else if (connectivityResult == ConnectivityResult.wifi) {
      if (await InternetConnectionChecker().hasConnection) {
        print("wifi data detected & internet connection confirmed.");
        return true;
      } else {
        print('No internet :( Reason:');
        return false;
      }
    } else {
      print(
          "Neither mobile data or WIFI detected, not internet connection found.");
      return false;
    }
  }

  final conn = SqfliteDatabaseHelper.instance;

  Future<List<AssetStatusModel>> fetchAllInfo() async {
    final dbClient = await conn.db;
    List<AssetStatusModel> assetStatusList = [];
    try {
      final maps = await dbClient!.query(SqfliteDatabaseHelper.peminjamanTable);
      for (var item in maps) {
        assetStatusList.add(AssetStatusModel.fromJson(item));
      }
    } catch (e) {
      print(e.toString());
    }
    return assetStatusList;
  }

  Future<void> deleteAllAssetStatusData() async {
    var dbClient = await conn.db;
    await dbClient!.delete(SqfliteDatabaseHelper.peminjamanTable);
  }

  // Future saveToPeminjamanWith(
  //     List<AssetStatusModel> assetStatusesLocalList) async {
  //   for (var i = 0; i < assetStatusesLocalList.length; i++) {
  //     DateTime? parseDateTime(String? dateTimeString) {
  //       if (dateTimeString == null || dateTimeString.isEmpty) {
  //         return null;
  //       }

  //       try {
  //         return DateTime.parse(dateTimeString);
  //       } catch (e) {
  //         print('Error parsing DateTime: $e');
  //         return null;
  //       }
  //     }

  //     // Format tanggal sesuai kebutuhan
  //     String formattedCreatedAt = assetStatusesLocalList[i].created_at != null
  //         ? DateFormat('yyyy-MM-dd HH:mm:ss.SSS')
  //             .format(assetStatusesLocalList[i].created_at!)
  //         : DateFormat('yyyy-MM-dd HH:mm:ss.SSS').format(DateTime.now());

  //     Map<String, dynamic> data = {
  //       "mobile_id": assetStatusesLocalList[i].mobile_id.toString(),
  //       "peti_id": assetStatusesLocalList[i].peti_id.toString(),
  //       "customer_id": assetStatusesLocalList[i].customer_id.toString(),
  //       "warehouse_id": assetStatusesLocalList[i].warehouse_id.toString(),
  //       "exit_at": assetStatusesLocalList[i].exit_at.toString(),
  //       "est_pengembalian":
  //           assetStatusesLocalList[i].est_pengembalian.toString(),
  //       "exit_pic": assetStatusesLocalList[i].exit_pic.toString(),
  //       "exit_warehouse": assetStatusesLocalList[i].exit_warehouse.toString(),
  //       "created_by": assetStatusesLocalList[i].created_by.toString(),
  //       "created_at": formattedCreatedAt,
  //     };

  //     final response = await http.post(
  //       Uri.parse(await getBaseUrl() + '/asset-status/store'),
  //       body: data,
  //     );

  //     if (response.statusCode == 200) {
  //       // print("Data uploaded successfully for index $i:");
  //       // print("Response body: ${response.body}");
  //       print("Saving Data saveToMysqlWith");
  //     } else {
  //       print(
  //           "Failed to upload data for index $i. Status code: ${response.statusCode}");
  //       print("Response body: ${response.body}");
  //     }
  //   }

  //   return true; // Pengunggahan berhasil
  // }

  Future<bool> saveToPeminjamanWith(
      List<AssetStatusModel> assetStatusesLocalList) async {
    const maxRequestsBeforeDelay = 25;
    const delayDuration = Duration(seconds: 3);

    int requestCounter = 0;

    await Future.forEach(assetStatusesLocalList, (assetStatus) async {
      DateTime? parseDateTime(String? dateTimeString) {
        if (dateTimeString == null || dateTimeString.isEmpty) {
          return null;
        }

        try {
          return DateTime.parse(dateTimeString);
        } catch (e) {
          print('Error parsing DateTime: $e');
          return null;
        }
      }

      // Format tanggal sesuai kebutuhan
      String formattedCreatedAt = assetStatus.created_at != null
          ? DateFormat('yyyy-MM-dd HH:mm:ss.SSS')
              .format(assetStatus.created_at!)
          : DateFormat('yyyy-MM-dd HH:mm:ss.SSS').format(DateTime.now());

      Map<String, dynamic> data = {
        "mobile_id": assetStatus.mobile_id.toString(),
        "peti_id": assetStatus.peti_id.toString(),
        "customer_id": assetStatus.customer_id.toString(),
        "warehouse_id": assetStatus.warehouse_id.toString(),
        "exit_at": assetStatus.exit_at.toString(),
        "est_pengembalian": assetStatus.est_pengembalian.toString(),
        "exit_pic": assetStatus.exit_pic.toString(),
        "exit_warehouse": assetStatus.exit_warehouse.toString(),
        "created_by": assetStatus.created_by.toString(),
        "created_at": formattedCreatedAt,
      };

      final response = await http.post(
        Uri.parse(await getBaseUrl() + '/asset-status/store'),
        body: data,
      );

      if (response.statusCode == 200) {
        print("Saving Data saveToMysqlWith");
      } else {
        print("Failed to upload data. Status code: ${response.statusCode}");
        print("Response body: ${response.body}");
      }

      // Increment counter
      requestCounter++;

      // Jeda 2 detik setiap 30 permintaan
      if (requestCounter % maxRequestsBeforeDelay == 0 &&
          requestCounter != assetStatusesLocalList.length) {
        await Future.delayed(delayDuration);
      }
    });

    return true; // Pengunggahan berhasil
  }

  Future<List> fetchAllCustomerInfo() async {
    final dbClient = await conn.db;
    List contactList = [];
    try {
      final maps = await dbClient!.query(SqfliteDatabaseHelper.peminjamanTable);
      for (var item in maps) {
        contactList.add(item);
      }
    } catch (e) {
      print(e.toString());
    }
    return contactList;
  }

  Future saveToMysql(List assetStatusesLocalList) async {
    DateTime? parseDateTime(String? dateTimeString) {
      if (dateTimeString == null || dateTimeString.isEmpty) {
        return null;
      }

      try {
        return DateTime.parse(dateTimeString);
      } catch (e) {
        print('Error parsing DateTime: $e');
        return null;
      }
    }

    for (var i = 0; i < assetStatusesLocalList.length; i++) {
// Format tanggal sesuai kebutuhan
      String formattedCreatedAt =
          assetStatusesLocalList[i]['created_at'] != null
              ? DateFormat('yyyy-MM-dd HH:mm:ss.SSS')
                  .format(assetStatusesLocalList[i]['created_at'])
              : DateFormat('yyyy-MM-dd HH:mm:ss.SSS').format(DateTime.now());

      Map<String, dynamic> data = {
        "mobile_id": assetStatusesLocalList[i]['mobile_id'].toString(),
        "peti_id": assetStatusesLocalList[i]['peti_id'].toString(),
        "customer_id": assetStatusesLocalList[i]['customer_id'].toString(),
        "warehouse_id": assetStatusesLocalList[i]['warehouse_id'].toString(),
        "exit_at": assetStatusesLocalList[i]['exit_at'].toString(),
        "est_pengembalian":
            assetStatusesLocalList[i]['est_pengembalian'].toString(),
        "exit_pic": assetStatusesLocalList[i]['exit_pic'].toString(),
        "exit_warehouse":
            assetStatusesLocalList[i]['exit_warehouse'].toString(),
        "status": assetStatusesLocalList[i]['status'].toString(),
        "created_by": assetStatusesLocalList[i]['created_by'].toString(),
        "created_at": formattedCreatedAt,
      };

      final response = await http.post(
          Uri.parse(await getBaseUrl() + '/asset-status/store'),
          body: data);
      if (response.statusCode == 200) {
        print(response.body);
        print("Saving Data saveToMysql");
      } else {
        print(response.statusCode);
      }
    }
  }

  Future<List<AssetStatusModel>> fetchFromApi() async {
    final response = await http.get(
      Uri.parse(await getBaseUrl() + '/asset-status'),
    );

    if (response.statusCode == 200) {
      List<dynamic> data = json.decode(response.body)['data']['asset_status'];
      List<AssetStatusModel> contactDBList = data
          .map(
              (item) => AssetStatusModel.fromJson(item as Map<String, dynamic>))
          .toList();

      return contactDBList;
    } else {
      throw Exception('Failed to fetch data from API Asset Status');
    }
  }
}