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/new_models/building.dart';
import 'package:test_sa/models/new_models/department.dart';
import 'package:test_sa/models/new_models/floor.dart';
import 'package:test_sa/models/new_models/site.dart';
import 'package:test_sa/models/new_models/task_request/task_request_model.dart';
import 'package:test_sa/models/timer_model.dart';
import '../../new_views/common_widgets/app_lazy_loading.dart';

class TaskRequestProvider extends ChangeNotifier {
  final pageItemNumber = 10;
  int? stateCode;
  bool isLoading = false;
  bool isSiteLoading = false;
  TaskData? taskRequestModel;
  List<Site>? siteList;

  void updateTaskModel(TaskData? value) {
    taskRequestModel = value;
    notifyListeners();
  }

  void refresh() {
    notifyListeners();
  }

  Future<void> addTask({
    required BuildContext context,
    required AddTaskModel task,
  }) async {
    showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
    Response response;
    try {
      response = await ApiManager.instance.post(URLs.addTaskUrl, body: task.toJson());

      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        notifyListeners();
        Fluttertoast.showToast(msg: context.translation.successfulRequestMessage);
        Navigator.pop(context);
      } else {
        Fluttertoast.showToast(msg: "${context.translation.failedRequestMessage} :${json.decode(response.body)['message']}");
      }
      Navigator.pop(context);
    } catch (error) {
      print(error);
      stateCode = -1;
      notifyListeners();
      Navigator.pop(context);
    }
  }

  //getTaskById......
  Future getTaskById({required int id, bool? showLoading = true}) async {
    try {
      isLoading = showLoading ?? true;
      taskRequestModel = null;
      notifyListeners();
      final response = await ApiManager.instance.get(URLs.getTaskByIdUrl + "?taskJobId=$id");
      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        taskRequestModel = TaskData.fromJson(json.decode(response.body)['data']);
        notifyListeners();
      }
      isLoading = false;
      notifyListeners();
    } catch (e) {
      log("getTask [error] : $e");
      isLoading = false;
      notifyListeners();
      return null;
    }
  }

  Future getSiteData({required int? siteId}) async {
    isSiteLoading = true;
    notifyListeners();
    try {
      Response response = await ApiManager.instance.get(URLs.getSiteAutoCompleteWithoutConditionSites + "?id=$siteId");
      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        List? siteData = json.decode(response.body)["data"];
        if (siteData != null && siteData.isNotEmpty) {
          taskRequestModel?.site = Site.fromJson(siteData.first);
        }
        taskRequestModel?.building = taskRequestModel?.site?.buildings?.firstWhere((element) => element.value == taskRequestModel?.installationBuilding?.value, orElse: () => Building());
        taskRequestModel?.floor = taskRequestModel?.building?.floors?.firstWhere((element) => element.value == taskRequestModel?.installationFloor?.value, orElse: () => Floor());
        taskRequestModel?.department = taskRequestModel?.floor?.departments?.firstWhere((element) => element.name == taskRequestModel?.installationDepartment?.name, orElse: () => Department());
      }
      isSiteLoading = false;
      notifyListeners();
      return response.statusCode;
    } catch (error) {
      isSiteLoading = false;
      stateCode = -1;
      notifyListeners();
      return -1;
    }
  }

  Future<bool> updateTaskByEngineer(TaskData? taskData) async {
    isLoading = true;
    Response response;
    try {
      response = await ApiManager.instance.post(URLs.updateTaskByEngineerUrl, body: taskData?.toEngineerUpdateJson() ?? taskRequestModel!.toEngineerUpdateJson());
      stateCode = response.statusCode;
      isLoading = false;
      notifyListeners();
      if (stateCode == 200) {
        return true;
      }
      return false;
    } catch (error) {
      isLoading = false;
      stateCode = -1;
      notifyListeners();
      return false;
    }
  }

  void updateTaskTimer({TimerModel? timer}) {
    taskRequestModel?.taskTimerModel = timer;
    if (timer?.startAt != null && timer?.endAt != null) {
      taskRequestModel?.timerModelList = taskRequestModel?.timerModelList ?? [];
      taskRequestModel?.timerModelList!.add(timer!);
    }
    notifyListeners();
  }

  Future<TaskData?> assignEngineerToHimself(num id) async {
    try {
      Response response = await ApiManager.instance.post(URLs.taskJobsAssignEngineerToHimself, body: {"taskJobId": id});
      if (response.statusCode >= 200 && response.statusCode < 300) {
        taskRequestModel = TaskData.fromJson(json.decode(response.body)["data"]);
        notifyListeners();
        return taskRequestModel;
      } else {
        return null;
      }
    } catch (error) {
      return null;
    }
  }

  Future<bool> engineerReject(Map<String, dynamic> body) async {
    try {
      Response response = await ApiManager.instance.post(URLs.taskJobsEngineerReject, body: body);
      if (response.statusCode >= 200 && response.statusCode < 300) {
        taskRequestModel = TaskData.fromJson(json.decode(response.body)["data"]);
        notifyListeners();
        return true;
      } else {
        return false;
      }
    } catch (error) {
      return false;
    }
  }
}
