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

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/generic_attachment_model.dart';
import 'package:test_sa/models/plan_preventive_visit/plan_preventive_visit_model.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;

  PlanPreventiveVisit? _planPreventiveVisit;
  late int _totalTabs = 4;
  TabController? tabController;
  bool _isReadOnly = false;

  bool get isReadOnly => _isReadOnly;

  set isReadOnly(bool value) {
    _isReadOnly = value;
    notifyListeners();
  }

  int get totalTabs => _totalTabs;

  set totalTabs(int value) {
    _totalTabs = value;
    notifyListeners();
  }

  List<GenericAttachmentModel> _ppmPlanAttachments = [];

  List<GenericAttachmentModel> get ppmPlanAttachments => _ppmPlanAttachments;

  set ppmPlanAttachments(List<GenericAttachmentModel> value) {
    _ppmPlanAttachments = value;
    notifyListeners();
  }

  PlanPreventiveVisit? get planPreventiveVisit => _planPreventiveVisit;

  set planPreventiveVisit(PlanPreventiveVisit? value) {
    _planPreventiveVisit = value;
    notifyListeners();
  } //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;
  //   }
  // }

  Future<PlanPreventiveVisit?> getPlanPreventiveVisitById(int id) async {
    try {
      isLoading = true;
      Response response = await ApiManager.instance.get(URLs.getPlanPreventiveVisitById + "?planPreventiveVisitId=$id");
      if (response.statusCode >= 200 && response.statusCode < 300) {
        ppmPlanAttachments = [];
        planPreventiveVisit = PlanPreventiveVisit.fromJson(json.decode(response.body)["data"]);
        if (planPreventiveVisit?.visitStatus?.value! == 1 || planPreventiveVisit?.visitStatus?.value == 3) {
          isReadOnly = true;
        } else {
          isReadOnly = false;
        }
        isLoading = false;
        notifyListeners();
        return planPreventiveVisit;
      }
      isLoading = false;
      notifyListeners();
      return null;
    } catch (error) {
      isLoading = false;
      notifyListeners();
      return null;
    }
  }

  Future<bool> updateVisitByEngineer({required int status}) async {
    isLoading = true;
    Response response;
    try {
      response = await ApiManager.instance.post(URLs.updateVisitByEngineer, body: planPreventiveVisit!.toJson(status: status));
      stateCode = response.statusCode;
      isLoading = false;
      notifyListeners();
      if (stateCode == 200) {
        return true;
      }
      return false;
    } catch (error) {
      isLoading = false;
      stateCode = -1;
      notifyListeners();
      return false;
    }
  }

  // Future<int> updateVisitByEngineer(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.updateVisitByEngineer, 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;
  //   }
  // }

  /// 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;
    }
  }

  bool validate() {
    bool isTimerPickerEnable = ApiManager.instance.assetGroup?.enabledEngineerTimer ?? false;

    if (isTimerPickerEnable) {
      if (planPreventiveVisit?.tbsTimer?.startAt == null && planPreventiveVisit?.ppMTimePicker == null) {
        Fluttertoast.showToast(msg: "Working Hours Required");
        return false;
      }
      if (planPreventiveVisit?.ppMTimePicker == null) {
        if (planPreventiveVisit?.tbsTimer?.startAt == null) {
          Fluttertoast.showToast(msg: "Working Hours Required");
          return false;
        }
        if (planPreventiveVisit?.tbsTimer?.endAt == null) {
          Fluttertoast.showToast(msg: "Please Stop The Timer");
          return false;
        }
      }
    } else {
      if (planPreventiveVisit?.tbsTimer?.startAt == null) {
        Fluttertoast.showToast(msg: "Working Hours Required");
        return false;
      }
      if (planPreventiveVisit?.tbsTimer?.endAt == null) {
        Fluttertoast.showToast(msg: "Please Stop The Timer");
        return false;
      }
    }

    //  if (model.startTime == null) {
    //   Fluttertoast.showToast(msg: "${context.translation.youHaveToSelect} ${context.translation.startTime}");
    //   return false;
    // }
    //  if (model.endTime == null) {
    //   Fluttertoast.showToast(msg: "${context.translation.youHaveToSelect} ${context.translation.endTime}");
    //   return false;
    // }
    // else if (model.travelHours == null) {
    //   Fluttertoast.showToast(msg: "${context.translation.youHaveToSelect} ${context.translation.travelingHours}");
    //   return false;
    // }
    // if (model.repairLocation == null) {
    //   Fluttertoast.showToast(msg: "${context.translation.youHaveToSelect} ${context.translation.repairLocation}");
    //   return false;
    // }
    // else if (model.assignedEmployeeId == null) {
    //   Fluttertoast.showToast(msg: "${context.translation.youHaveToSelect} ${context.translation.assignedEmployee}");
    //   return false;
    // }
    //write all other missing conditions..

    return true;
  }
}
