import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:gen_service/Models/HelpAndComplaintModels/complaintDetailsResponse.dart';
import 'package:gen_service/Models/HelpAndComplaintModels/jobCardProductsResponse.dart';
import 'package:gen_service/Services/api_calling.dart';
import 'package:provider/provider.dart';

import '../Models/CommonResponse.dart';
import '../Models/HelpAndComplaintModels/ComplaintListResponse.dart';
import '../Models/HelpAndComplaintModels/GeneratorListResponse.dart';
import '../Models/HelpAndComplaintModels/DropDownsListResponse.dart';

class HelpAndComplaintProvider extends ChangeNotifier {
  bool _isLoading = false;
  String? _errorMessage;
  ComplaintListResponse? _complaintListResponse;

  complaintDetailsResponse? _complaintDetailsResponse;
  jobCardProductsResponse? _jobCardResponse;

  bool get isLoading => _isLoading;
  String? get errorMessage => _errorMessage;
  ComplaintListResponse? get complaintListResponse => _complaintListResponse;

  GeneratorListResponse? _generatorListResponse;

  GeneratorListResponse? get generatorListResponse => _generatorListResponse;

  DropDownsListResponse? _dropDownsListResponse;
  DropDownsListResponse? get dropDownsListResponse => _dropDownsListResponse;

  complaintDetailsResponse? get compDetailsResponse => _complaintDetailsResponse;
  jobCardProductsResponse? get jobCardResponse => _jobCardResponse;

  List<bool> _starStates = [false, false, false, false, false];
  var _rating = 0;

  List<bool> get starStates => _starStates;
  int get rating => _rating;


  set rating(int value) {
    _rating = value;
    notifyListeners();
  }

  set starStates(List<bool> value) {
    _starStates = value;
    notifyListeners();
  }


  void updateStarStates(int rating, List<bool> starStates) {

    starStates.fillRange(0, starStates.length, false);

    for (int i = 0; i < rating; i++) {
      starStates[i] = true;
    }
    notifyListeners();
  }

  ///----------------------------------------------
  /// Fetch Complaints List
  ///----------------------------------------------
  Future<void> fetchComplaintsList({
    required String accId,
    required String sessionId,
    required String genId,
  }) async {
    _setLoading(true);
    try {
      final response = await ApiCalling.fetchComplaintsListApi(accId, sessionId, genId);
      if (response != null && response.error == "0") {
        _complaintListResponse = response;
        _errorMessage = null;
      } else {
        _errorMessage = response?.message ?? "Failed to fetch complaints";
      }
    } catch (e) {
      _errorMessage = "Error fetching complaints: $e";
      debugPrint(_errorMessage);
    } finally {
      _setLoading(false);
    }
  }

  ///----------------------------------------------
  /// Add Complaint
  ///----------------------------------------------
  Future<CommonResponse?> addComplaint({
    required String accId,
    required String sessionId,
    required String genId,
    required String categoryId,
    required String descriptionId,
    required String note,
    required String typeId,
  }) async {
    _setLoading(true);
    try {
      final response = await ApiCalling.addComplaintApi(
        accId,
        sessionId,
        genId,
        categoryId,
        descriptionId,
        note,
        typeId,
      );

      if (response != null && response.error == "0") {
        // Optionally refresh list after successful submission
        await fetchComplaintsList(accId: accId, sessionId: sessionId, genId: genId);
        return response;
      } else {
        _errorMessage = response?.message ?? "Failed to add complaint";
        return response;
      }
    } catch (e) {
      _errorMessage = "Error adding complaint: $e";
      debugPrint(_errorMessage);
      return null;
    } finally {
      _setLoading(false);
    }
  }


  //  NEW FUNCTION: Fetch Generator List for Help Screen
  Future<void> fetchGeneratorList({
    required String accId,
    required String sessionId,
  }) async {
    _setLoading(true);
    try {
      final response = await ApiCalling.addGeneratorListApi(accId, sessionId);
      if (response != null && response.error == "0") {
        _generatorListResponse = response;
        _errorMessage = null;
      } else {
        _errorMessage = response?.message ?? "Failed to fetch generator list";
      }
    } catch (e) {
      _errorMessage = "Error fetching generator list: $e";
      debugPrint(_errorMessage);
    } finally {
      _setLoading(false);
    }
  }


  ///----------------------------------------------
  /// Fetch Complaint Dropdowns List
  ///----------------------------------------------
  Future<void> fetchComplaintDropdowns({
    required String accId,
    required String sessionId,
    required String genId,
  }) async {
    _setLoading(true);
    try {
      final response = await ApiCalling.dropdownsListApi(accId, sessionId, genId);
      if (response != null && response.error == "0") {
        _dropDownsListResponse = response;
        _errorMessage = null;
      } else {
        _errorMessage = response?.message ?? "Failed to fetch dropdown data";
      }
    } catch (e) {
      _errorMessage = "Error fetching dropdown list: $e";
      debugPrint(_errorMessage);
    } finally {
      _setLoading(false);
    }
  }



  Future<void> fetchComplaintDetailsAPI(String accId, String sessionId,complaintId) async {
    _isLoading = true;
    _errorMessage = null;
    notifyListeners();
    try {
      final response = await ApiCalling.complaintDetailsAPI(accId, sessionId,complaintId);

      if (response != null) {
        if (response.error == "0") {
          _complaintDetailsResponse = response;
          updateStarStates(int.parse(response.serviceDetails?.firstOrNull?.rating.toString()??"0"), _starStates);
        } else {
          _errorMessage = response.message ?? "Something went wrong!";
        }
      } else {
        _errorMessage = "No response from server.";
      }
    } catch (e) {
      _errorMessage = "Failed to fetch dashboard: $e";
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  Future<void> updateRatingForTechnician(String accId, String sessionId,complaintId,rating) async {

    // _errorMessage = null;
    notifyListeners();
    try {
      final response = await ApiCalling.updateTechRatingAPI(accId, sessionId,complaintId,rating);

      if (response != null) {
        if (response.error == "0") {
          fetchComplaintDetailsAPI(accId, sessionId,complaintId);
        } else {
          // _errorMessage = response.message ?? "Something went wrong!";
        }
      } else {
        // _errorMessage = "No response from server.";
      }
    } catch (e) {
      _errorMessage = "Failed to fetch dashboard: $e";
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  Future<void> fetchJobCardProductDetails(String accId, String sessionId,jobCardId) async {

    _errorMessage = null;
    notifyListeners();
    try {
      final response = await ApiCalling.jobCardProductDetailsAPI(accId, sessionId,jobCardId);

      if (response != null) {
        if (response.error == "0") {
          _jobCardResponse = response;
        } else {
          _errorMessage = response.message ?? "Something went wrong!";
        }
      } else {
        _errorMessage = "No response from server.";
      }
    } catch (e) {
      _errorMessage = "Failed to fetch dashboard: $e";
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }



  ///----------------------------------------------
  /// Private Helpers
  ///----------------------------------------------
  void _setLoading(bool value) {
    _isLoading = value;
    notifyListeners();
  }

  void clearData() {
    _complaintListResponse = null;
    _errorMessage = null;
    notifyListeners();
  }
}
