import 'package:flutter/material.dart';
import 'package:generp/Models/hrmModels/attendanceRequestDetailsResponse.dart';
import 'package:provider/provider.dart';

import '../../Models/ordersModels/commonResponse.dart';
import '../../services/api_calling.dart';
import '../HomeScreenNotifier.dart';

class AttendanceDetailsProvider extends ChangeNotifier {
  attendanceRequestDetailsResponse? _response;
  bool _isLoading = false;
  String? _errorMessage;
  bool _isSubmitting = false;
  bool get isSubmitting => _isSubmitting;

  CommonResponse? _RejectResponse;
  CommonResponse? get addResponse => _RejectResponse;

  attendanceRequestDetailsResponse? get response => _response;
  bool get isLoading => _isLoading;
  String? get errorMessage => _errorMessage;

  Future<void> fetchAttendanceRequestDetail(context, String requestId) async {
    _isLoading = true;
    _errorMessage = null;
    _response = null;
    notifyListeners();

    try {
      final provider = Provider.of<HomescreenNotifier>(context, listen: false);
      final result = await ApiCalling.attendanceRequestDetailAPI(
        provider.empId,
        provider.session,
        requestId,
      );

      if (result != null) {
        _response = result;
      } else {
        _errorMessage = "No data found!";
      }
    } catch (e) {
      _errorMessage = "Something went wrong: $e";
    }

    _isLoading = false;
    notifyListeners();
  }

  Future<void> rejectApproveAttendanceRequest(
    BuildContext context, {
    required String mode,
    required String type,
    required String remarks,
    required String id,
  }) async {
    _isSubmitting = true;
    _errorMessage = null;
    _RejectResponse = null;
    notifyListeners();

    try {
      final homeProvider = Provider.of<HomescreenNotifier>(
        context,
        listen: false,
      );
      print("############################+++++++++++++++++##########");

      final result = await ApiCalling.attendanceRequestApproveRejectAPI(
        homeProvider.session,
        homeProvider.empId,
        mode,
        type,
        remarks,
        id,
      );

      if (result != null) {
        _RejectResponse = result;
        if (result.error != null && result.error!.isNotEmpty) {
          _errorMessage = result.error;
        } else {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              content: Text("Attendance request rejected successfully."),
            ),
          );
        }
      } else {
        _errorMessage = "Failed to reject attendance request!";
      }
    } catch (e) {
      _errorMessage = "Error rejecting attendance request: $e";
    }

    _isSubmitting = false;
    notifyListeners();
  }
}
