import 'dart:convert';

import 'package:flutter/material.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';

class CleanerProvider extends ChangeNotifier {
  bool _isLoading = false;
  bool get isLoading => _isLoading;

  // Search results
  List<dynamic>? _searchResults;
  List<dynamic>? get searchResults => _searchResults;

  // State code for error handling
  int? _stateCode;
  int? get stateCode => _stateCode;

  // TODO: Add your cleaner request model here
  // CleanerRequestModel? _currentCleanerRequest;
  // CleanerRequestModel? get currentCleanerRequest => _currentCleanerRequest;

  Future<void> getCleanerRequestById({required int id}) async {
    _isLoading = true;
    notifyListeners();

    try {
      // TODO: Implement API call to fetch cleaner request details
      // Example:
      // final response = await CleanerApiService.getCleanerRequestById(id);
      // _currentCleanerRequest = response.data;

      await Future.delayed(const Duration(seconds: 1)); // Simulating API call

    } catch (e) {
      debugPrint('Error fetching cleaner request: $e');
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  /// Search plan recurrent tasks
  Future<int> searchPlanRecurrentTasks({
    required int pageSize,
    required int pageNumber,
    int? siteId,
    int? buildingId,
    int? floorId,
    int? departmentId,
    int? roomId,
  }) async {
    if (_isLoading == true) return -2;
    _isLoading = true;
    notifyListeners();

    Response response;
    try {
      response = await ApiManager.instance.post(
        URLs.searchPlanRecurrentTaskListSearch,
        body: {
          "pageSize": pageSize,
          "pageNumber": pageNumber,
          "siteId": siteId,
          "buildingId": buildingId,
          "floorId": floorId,
          "departmentId": departmentId,
          "roomId": roomId,
        },
      );

      _stateCode = response.statusCode;

      if (response.statusCode >= 200 && response.statusCode < 300) {
        // client's request was successfully received
        final responseData = json.decode(response.body);
        _searchResults = responseData["data"] as List<dynamic>?;
      } else {
        _searchResults = null;
      }

      _isLoading = false;
      notifyListeners();
      return response.statusCode;
    } catch (error) {
      debugPrint('Error searching plan recurrent tasks: $error');
      _isLoading = false;
      _stateCode = -1;
      _searchResults = null;
      notifyListeners();
      return -1;
    }
  }

  /// Search plan recurrent tasks and return results directly without provider state
  Future<Map<String, dynamic>> searchPlanRecurrentTasksList({
    required int pageSize,
    required int pageNumber,
    int? siteId,
    int? buildingId,
    int? floorId,
    int? departmentId,
    int? roomId,
    int? taskTypeId,
  }) async {
    Response response;
    try {
      response = await ApiManager.instance.post(
        URLs.searchPlanRecurrentTaskListSearch,
        body: {
          "pageSize": pageSize,
          "pageNumber": pageNumber,
          "siteId": siteId,
          "buildingId": buildingId,
          "floorId": floorId,
          "departmentId": departmentId,
          "roomId": roomId,
          "taskTypeId": taskTypeId,
        },
      );

      if (response.statusCode >= 200 && response.statusCode < 300) {
        final responseData = json.decode(response.body);
        return {
          "data": responseData["data"] as List<dynamic>? ?? [],
          "totalRows": responseData["totalRows"] as int? ?? 0,
        };
      }
      return {"data": [], "totalRows": 0};
    } catch (error) {
      debugPrint('Error searching plan recurrent tasks: $error');
      return {"data": [], "totalRows": 0};
    }
  }

  /// Check if QR code matches the same room for a plan recurrent task
  Future<bool> checkQRSameRoom({
    required int planRecurrentTaskId,
    required String qrCode,
  }) async {
    Response response;
    try {
      response = await ApiManager.instance.post(
        URLs.checkQRSameRoom,
        body: {
          "planRecurrentTaskId": planRecurrentTaskId,
          "qrCode": qrCode,
        },
        showToast: false, // Disable automatic toast message
      );

      if (response.statusCode >= 200 && response.statusCode < 300) {
        final responseData = json.decode(response.body);
        // Assuming the API returns a boolean in the data field or a success flag
        return responseData["data"] == true || responseData["isSuccess"] == true;
      }
      return false;
    } catch (error) {
      debugPrint('Error checking QR same room: $error');
      return false;
    }
  }

  /// Check if QR code matches the same room for a plan recurrent task
  /// Returns a map with success status and message from backend
  Future<Map<String, dynamic>> checkQRSameRoomWithMessage({
    required int planRecurrentTaskId,
    required String qrCode,
  }) async {
    Response response;
    try {
      response = await ApiManager.instance.post(
        URLs.checkQRSameRoom,
        body: {
          "planRecurrentTaskId": planRecurrentTaskId,
          "qrCode": qrCode,
        },
        showToast: false, // Disable automatic toast message
      );

      // Parse the response body to extract the message
      final responseData = json.decode(response.body);

      if (response.statusCode >= 200 && response.statusCode < 300) {
        // Success response
        final isValid = responseData["data"] == true || responseData["isSuccess"] == true;
        return {
          "success": isValid,
          "message": responseData["message"] ?? (isValid ? "QR code validated successfully" : "QR code validation failed"),
        };
      } else {
        // Error response - extract the exact error message from backend
        return {
          "success": false,
          "message": responseData["message"] ?? "QR code validation failed",
        };
      }
    } catch (error) {
      debugPrint('Error checking QR same room: $error');
      return {
        "success": false,
        "message": "Failed to validate QR code. Please check your connection and try again.",
      };
    }
  }

  /// Scan QR Code and get task details
  /// Returns a map with success status, message, and data from backend
  Future<Map<String, dynamic>> scanQRCode({
    required String qrCode,
  }) async {
    Response response;
    try {
      response = await ApiManager.instance.post(
        URLs.scanQRCode,
        body: {
          "qrCode": qrCode,
        },
        showToast: false, // Disable automatic toast message
      );

      // Parse the response body to extract the message
      final responseData = json.decode(response.body);

      if (response.statusCode >= 200 && response.statusCode < 300) {
        // Success response
        return {
          "success": true,
          "data": responseData["data"],
          "message": responseData["message"] ?? "QR code scanned successfully",
        };
      } else {
        // Error response - extract the exact error message from backend
        return {
          "success": false,
          "data": null,
          "message": responseData["message"] ?? "QR code scan failed",
        };
      }
    } catch (error) {
      debugPrint('Error scanning QR code: $error');
      return {
        "success": false,
        "data": null,
        "message": "Failed to scan QR code. Please check your connection and try again.",
      };
    }
  }

  /// Proceed with OneTime Task request
  /// Returns a map with success status, message, and data from backend
  Future<Map<String, dynamic>> proceedOneTimeTask({
    required int oneTimeSettingId,
    required int siteId,
    required int buildingId,
    required int floorId,
    required int departmentId,
    required int roomId,
  }) async {
    Response response;
    try {
      response = await ApiManager.instance.post(
        URLs.proceedRequest,
        body: {
          "oneTimeSettingId": oneTimeSettingId,
          "siteId": siteId,
          "buildingId": buildingId,
          "floorId": floorId,
          "departmentId": departmentId,
          "roomId": roomId,
        },
        showToast: false, // Disable automatic toast message
      );

      // Parse the response body to extract the message
      final responseData = json.decode(response.body);

      if (response.statusCode >= 200 && response.statusCode < 300) {
        // Success response
        return {
          "success": true,
          "data": responseData["data"],
          "message": responseData["message"] ?? "Request proceeded successfully",
        };
      } else {
        // Error response - extract the exact error message from backend
        return {
          "success": false,
          "data": null,
          "message": responseData["message"] ?? "Failed to proceed with request",
        };
      }
    } catch (error) {
      debugPrint('Error proceeding with request: $error');
      return {
        "success": false,
        "data": null,
        "message": "Failed to proceed with request. Please check your connection and try again.",
      };
    }
  }

  /// Get OneTime Task by ID using getRequestById endpoint
  Future<Map<String, dynamic>> getOneTimeTaskById({
    required int id,
  }) async {
    Response response;
    try {
      response = await ApiManager.instance.get(
        '${URLs.getRequestById}?id=$id',
      );

      // Parse the response body
      final responseData = json.decode(response.body);

      if (response.statusCode >= 200 && response.statusCode < 300) {
        // Success response
        return {
          "success": true,
          "data": responseData["data"],
          "message": responseData["message"] ?? "Task retrieved successfully",
        };
      } else {
        // Error response
        return {
          "success": false,
          "data": null,
          "message": responseData["message"] ?? "Failed to retrieve task",
        };
      }
    } catch (error) {
      debugPrint('Error getting one time task: $error');
      return {
        "success": false,
        "data": null,
        "message": "Failed to retrieve task. Please check your connection and try again.",
      };

    }
  }

  /// Complete OneTime Task
  Future<Map<String, dynamic>> completeOneTimeTask({
    required int id,
    required List<Map<String, dynamic>> instructions,
    List<Map<String, dynamic>>? attachments,
  }) async {
    Response response;
    try {
      response = await ApiManager.instance.post(
        URLs.completeRequest,
        body: {
          "id": id,
          "instructions": instructions,
          "attachments": attachments ?? [],
        },
        showToast: false,
      );

      final responseData = json.decode(response.body);

      if (response.statusCode >= 200 && response.statusCode < 300) {
        return {
          "success": true,
          "data": responseData["data"],
          "message": responseData["message"] ?? "Task completed successfully",
        };
      } else {
        return {
          "success": false,
          "data": null,
          "message": responseData["message"] ?? "Failed to complete task",
        };
      }
    } catch (error) {
      debugPrint('Error completing one time task: $error');
      return {
        "success": false,
        "data": null,
        "message": "Failed to complete task. Please check your connection and try again.",
      };
    }
  }

  void reset() {
    _isLoading = false;
    _searchResults = null;
    _stateCode = null;
    // _currentCleanerRequest = null;
    notifyListeners();
  }
}
