import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:generp/Utils/SharedpreferencesService.dart';
import 'package:generp/Utils/commonServices.dart';
import 'package:generp/screens/LoginScreen.dart';
import 'package:generp/screens/inventory/GeneratorPartDetailsScreen.dart';
import 'package:generp/services/api_calling.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:qr_code_scanner/qr_code_scanner.dart';

import '../Models/Inventory_Part_details_response.dart';
import '../Models/generatorComplaintResponse.dart';
import '../screens/genTracker/ComplaintHistory.dart';
import '../screens/splash.dart';

class InventoryProvider extends ChangeNotifier {
  PermissionStatus _cameraPermissionStatus = PermissionStatus.denied;
  final GlobalKey scannerKey = GlobalKey(debugLabel: 'QR');
  PartData _partData = PartData();
  List<C_List> _complaintList = [];
  bool _isLoading = false;
  bool _hasPermission = false;
  QRViewController? _qrViewController;
  String? _partID = "";
  String _description = '';
  String _quantity = '';
  String _quantityError = '';
  String _descriptionError = '';
  String _issuetype = "";

  String get issuetype => _issuetype;
  set issuetype(value) {
    _issuetype = value;
  }

  String get quantityError => _quantityError;
  String get descriptionError => _descriptionError;
  bool get isButtonEnabled => _quantity.isNotEmpty && _description.isNotEmpty;
  String? get partID => _partID;

  PartData get partData => _partData;
  List<C_List> get complaintList => _complaintList;

  bool get hasPermission => _hasPermission;

  QRViewController? get qrViewController => _qrViewController;

  Future<void> checkPermission1() async {
    // Check camera permissions
    var status = await Permission.camera.status;
    try {
      if (status.isGranted) {
        _hasPermission = true;
      } else if (status.isDenied || status.isRestricted) {
        // Request camera permissions if denied or restricted
        await Permission.camera.request();
        status = await Permission.camera.request();
        if (status.isGranted) {
          _hasPermission = true;
        } else {
          _hasPermission = false;
        }
      }
    } catch (e) {}
  }

  Future<void> requestCameraPermission() async {
    PermissionStatus status = await Permission.camera.request();

    _cameraPermissionStatus = status;
    // print(_cameraPermissionStatus);

    try {
      if (_cameraPermissionStatus.isGranted) {
        _hasPermission = true;
      } else if (_cameraPermissionStatus.isDenied ||
          _cameraPermissionStatus.isRestricted ||
          _cameraPermissionStatus.isPermanentlyDenied) {
        _hasPermission = false;
        await Permission.camera.request();
      }
    } catch (e) {}
  }

  void onQRViewCreated(QRViewController controller, from, context) {
    // print("QRVIEW");
    _qrViewController = controller;
    controller.scannedDataStream.listen((scanData) {
      controller.pauseCamera();
      if (from == "inventory") {
        _partID = scanData.code;
        notifyListeners();
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => GeneratorPartDetailsScreen()),
        );
      } else if (from == "pendingComplaints") {
        _partID = scanData.code;
        notifyListeners();
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => Complainthistory(genHashID: scanData.code),
          ),
        );
      }
    });
  }

  Future<void> LoadPartDetailsApifunction(
    homeProvider,
    BuildContext context,
    from,
    partId,
  ) async {
    try {
      final data = await ApiCalling.LoadPartDetailsAPI(
        homeProvider.empId,
        homeProvider.session,
        partId,
      );

      if (data != null) {
        if (data.error == 0) {
          _partData = data.partData!;
          _partID = partId;
          if (from == "inventory") {
            _qrViewController!.pauseCamera();
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => GeneratorPartDetailsScreen(),
              ),
            );
          }
        } else if (data.error == 1) {
          toast(context, "Enter Correct ID");
        } else {}

        notifyListeners();
      }
    } on Error catch (e) {
      print(e.toString());
    }
  }

  Future<void> LoadgeneratorComplaintHistoryApifunction(
    homeProvider,
    BuildContext context,
    from,
    genID,
  ) async {
    try {
      final data = await ApiCalling.LoadGeneratorComplaintListAPI(
        homeProvider.empId,
        homeProvider.session,
        genID,
        "Open",
      );

      if (data != null) {
        if (data.sessionExists == 1) {
          if (data.error == 0) {
            _complaintList = data.list!;
            _isLoading = false;

            _qrViewController!.pauseCamera();
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => Complainthistory(genHashID: genID),
              ),
            );
            notifyListeners();
          } else {
            _isLoading = true;
            print("error");
          }
        } else {
          _isLoading = true;
          // SharedpreferencesService().clearPreferences();
          // toast(context, "Your Session expired, Please Login Again!");
          // Navigator.push(
          //   context,
          //   MaterialPageRoute(builder: (context) => Splash()),
          // );
        }
      } else {
        _isLoading = true;
        toast(context, "Something Went Wrong, Please try again!");
        print("error2");
      }
    } on Error catch (e) {
      print(e.toString());
    }
  }

  void updateQuantity(String issueQuantity) {
    _quantity = issueQuantity;
    _quantityError = '';
    notifyListeners();
  }

  void updateDescription(String issueDescription) {
    _description = issueDescription;
    _descriptionError = '';
    notifyListeners();
  }

  bool _validate(String issueQuantity, String issueDescription) {
    _quantityError = '';
    _descriptionError = '';

    if (issueQuantity.isEmpty) {
      _quantityError = "Please enter a valid email address";
    }

    if (issueDescription.isEmpty) {
      _descriptionError = "Please enter your password";
    }

    notifyListeners();
    return _quantityError.isEmpty && _descriptionError.isEmpty;
  }

  Future<void> StockRecieveIssueAPI(
    homeProvider,
    context,
    issueQuantity,
    issueDescription,
    partID,
    type,
  ) async {
    try {
      if (!_validate(issueQuantity, issueDescription)) return;
      final data = await ApiCalling.InventoryUpdateStockAPI(
        homeProvider.empId,
        homeProvider.session,
        issueQuantity,
        issueDescription,
        partID,
        type,
      );

      if (data != null) {
        if (data.error == 0) {
          toast(context, "Updated Successfully!");
          Navigator.pop(context);

          LoadPartDetailsApifunction(homeProvider, context, "", partID);
        } else {
          toast(context, "Updated Failed!");
        }
        notifyListeners();
      }
    } on Error catch (e) {
      print(e.toString());
    }
  }
}
