import 'dart:convert';
import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:http/http.dart';
import 'package:test_sa/controllers/api_routes/api_manager.dart';
import 'package:test_sa/controllers/api_routes/urls.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/models/ppm/ppm.dart';
import 'package:test_sa/models/ppm/ppm_search.dart';
import 'package:test_sa/models/user.dart';

import '../../../new_views/common_widgets/app_lazy_loading.dart';

class PpmProvider extends ChangeNotifier {
  // number of items call in each request
  final pageItemNumber = 12;

  //reset provider data
  void reset() {
    ppms = null;
    nextPage = true;
    stateCode = null;
  }

  // state code of current request to defied error message
  // like 400 customer request failed
  // 500 service not available
  int? stateCode; // Now nullable

  // true if there is next page in product list and false if not
  bool nextPage = true;

  // list of user requests
  List<Ppm>? ppms; // Now nullable

  // when requests in-process _loading = true
  // done _loading = true
  // failed _loading = false
  bool isLoading = false;

  PpmSearch visitsSearch = PpmSearch();

  /// return -2 if request in progress
  /// return -1 if error happen when sending request
  /// return state code if request complete may be 200, 404 or 403
  /// for more details check http state manager
  /// lib\controllers\http_status_manger\http_status_manger.dart
  Future<int> getVisits({
    required String host,
    required User user,
    //VisitsSearch visitsSearch,
  }) async {
    if (isLoading == true) return -2;
    isLoading = true;
    if (ppms?.isEmpty ?? true) notifyListeners();
    late Response response; // Using 'late' for initialization later

    try {
      Map<String, dynamic> body = {};
      body.addAll(visitsSearch.toJson());
      body["pageNumber"] = (ppms?.length ?? 0) ~/ pageItemNumber + 1;
      body["pageSize"] = pageItemNumber;

      response = await ApiManager.instance.post(
        URLs.getRegularVisits,
        body: body,
      );
    } catch (error) {
      isLoading = false;
      stateCode = -1;
      notifyListeners();
      return -1;
    }
    stateCode = response.statusCode;
    if (response.statusCode >= 200 && response.statusCode < 300) {
      // client's request was successfully received
      try {
        List requestsListJson = json.decode(response.body)["data"];
        List<Ppm> visits = requestsListJson.map((request) => Ppm.fromJson(request)).toList();
        ppms ??= []; // Initialize if null
        ppms!.addAll(visits); // Use '!' since ppms is now non-nullable after initialization
        notifyListeners();
        if (visits.length == pageItemNumber) {
          nextPage = true;
        } else {
          nextPage = false;
        }
      } catch (error) {
        log(error.toString()); // Convert error to string
        isLoading = false;
        stateCode = -1;
        notifyListeners();
        return -1;
      }
    }
    isLoading = false;
    notifyListeners();
    return response.statusCode;
  }

  Future<Ppm?> getPpmById(num id) async {
    // Return type is nullable
    try {
      visitsSearch.id = id;
      visitsSearch.pageNumber = 1;
      visitsSearch.pageSize = 3;
      Response response = await ApiManager.instance.post(URLs.getRegularVisits, body: visitsSearch.toJson());

      if (response.statusCode >= 200 && response.statusCode < 300) {
        List requestsListJson = json.decode(response.body)["data"];
        List<Ppm> visits = requestsListJson.map((request) => Ppm.fromJson(request)).toList();
        return visits.firstWhere((element) => id == element.id, orElse: null); // Handle case where no element is found
      }
      return null;
    } catch (error) {
      return null;
    }
  }

  /// return -2 if request in progress
  /// return -1 if error happen when sending request
  /// return state code if request complete may be 200, 404 or 403
  /// for more details check http state manager
  /// lib\controllers\http_status_manger\http_status_manger.dart
  Future<int> updateGroupOfVisits({
    required String host,
    required User user,
    // VisitsGroup group,
  }) async {
    late Response response; // Using 'late' for initialization later

    try {
      Map<String, dynamic> body = {} /*group.toJson()*/;

      response = await ApiManager.instance.post(
        URLs.getRegularVisits,
        body: body,
      );
      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        // client's request was successfully received
        reset();
        notifyListeners();
      }

      return response.statusCode;
    } catch (error) {
      isLoading = false;
      stateCode = -1;
      notifyListeners();
      return -1;
    }
  }

  Future<Ppm?> getPentry({required String host, required User user, required int id}) async {
    // Return type is nullable
    Response response;
    response = await ApiManager.instance.get("${URLs.getPentry}/$id");
    Ppm? pantry; // Now nullable
    if (response.statusCode >= 200 && response.statusCode < 300) {
      pantry = Ppm.fromJson(json.decode(utf8.decode(response.bodyBytes)));
    }
    return pantry;
  }

  Future<int> updatePentry(
    BuildContext context, {
    required User user,
    required Ppm ppm,
  }) async {
    try {
      ppm.visitTimers?.add(
        VisitTimers(
          id: 0,
          startDateTime: ppm.tbsTimer?.startAt!.toIso8601String(), // Handle potential null
          endDateTime: ppm.tbsTimer?.endAt?.toIso8601String(), // Handle potential null
          workingHours: ((ppm.tbsTimer?.durationInSecond ?? 0) / 60 / 60),
        ),
      );
      showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
      late Response response; // Using 'late' for initialization later
      Map<String, dynamic> body = ppm.copyWith(assignedEmployeeId: user.userName, tbsTimer: ppm.tbsTimer).toJson();
      response = await ApiManager.instance.put(URLs.updatePentry, body: body);
      if (response.statusCode >= 200 && response.statusCode < 300) {
        reset(); //visit.status = pentry.ppmVisitStatus;
        notifyListeners();
        Fluttertoast.showToast(msg: context.translation.successfulRequestMessage);
        Navigator.of(context).pop();
      } else {
        Fluttertoast.showToast(msg: "${context.translation.failedToCompleteRequest} ${jsonDecode(response.body)["message"]}");
      }
      Navigator.of(context).pop();
      return response.statusCode;
    } catch (error) {
      return -1;
    }
  }
}
