import 'package:get/get.dart';
import 'package:intl/intl.dart';

import 'package:rounded_loading_button_plus/rounded_loading_button.dart';
import '../../Data/Repository/Notification/Notificationrepository.dart';
import '../../Data/Repository/Rider/get_rider_repo.dart';
import '../../Data/Repository/update_delivery/create_delivery.dart';
import '../../Data/Repository/update_delivery/update_delivery.dart';
import '../../Helper/Logger.dart';
import '../../Helper/toast.dart';
import '../../Model/Request/Notification/Notification_request_rider.dart';
import '../../Model/Request/Notification/Notificationrequest.dart';
import '../../Model/Request/create_delivery_request/create_delivery_request.dart';
import '../../Model/Request/update_delivery/update_delivery.dart';
import '../../Model/Response/Notification/Notificationresponse.dart';
import '../../Model/Response/Orders/Getorderresponse.dart';
import '../../Model/Response/Riders/get_rider_model.dart';
import '../../Model/Response/Summary/Getsummarysresponse.dart';
import '../../Model/Response/create_delivery_response/create_delivery_request.dart';
import '../../Model/Response/update_delivery_response/update_delivery_response.dart';
import '../../View/Home/Homeview.dart';

class RiderAssignController extends GetxController {

  List <GetRiderDetails> riderDetails = [];

  final RidersRepository ridersRepository = RidersRepository();


  getRiders(appLocationId) async {
    GetRiderPoolsModel? result = await ridersRepository.getRiders(1);
    getRidersResult(result!);
  }

  bool isSelectAll = false;
  List riderFcmToken = [];
  int? riderUserIdList;
  int? partnerId;
  int? shiftId;
  String? riderStatus;
  RxBool shimmer = true.obs;
  String? assignTime;
  bool isIdle = false;

  RoundedLoadingButtonController btnNotifyRiderController = RoundedLoadingButtonController();


  getRidersResult(GetRiderPoolsModel data) {
    if (data.code == 200) {
      logger.i('RiderPool ${data.details}');
      if (data.details!.isNotEmpty) {
        for (int i = 0; i < data.details!.length; i++) {
          var index = riderDetails.indexWhere(
                  (element) =>
              element.userid == data.details![i].userid);
          if (index == -1) {
            riderDetails.add(data.details![i]);
          }
        }
      }
      logger.i('riderDetails $riderDetails');
      if (isSelectAll == true) {
        riderFcmToken.clear();
        riderUserIdList = 0;
        partnerId = 0;
        shiftId = 0;
        riderStatus = '';

        for (var riderDetail in riderDetails) {
          riderFcmToken.add(riderDetail.userfcmtoken);
          riderUserIdList = riderDetail.userid!;
          partnerId = riderDetail.partnerid!;
          shiftId = riderDetail.shiftid!;
          riderStatus = riderDetail.status;
          print('shiftId $shiftId');
        }
      } else {
        riderFcmToken.clear();
        riderUserIdList = 0;
        partnerId = 0;
        shiftId = 0;
        riderStatus = '';
      }
      logger.i('riderFcmToken  $riderFcmToken');
      logger.i('partnerIdinprint  $partnerId');
      logger.i('shiftId $shiftId');
      logger.i('riderStatus $riderStatus');
      shimmer.value = false;
      update();
    }
    else {
      shimmer.value = false;
      update();
      Toast.showToast("${data.message}");
    }
  }

  updateDelivery(OrderDetails data) async {
    assignTime = DateFormat("yyyy-MM-dd HH:mm:ss").format(DateTime.now());


    updateDeliveryResult(
      UpdateDeliveryRequest(
        deliveryid: data.deliveryid,
        userid: riderUserIdList,
        orderheaderid: data.orderheaderid,
        assigntime: assignTime,
        orderstatus: 'pending',
      ),
    );
  }

  UpdateDeliveryRepository updateDeliveryRepository = UpdateDeliveryRepository();

  updateDeliveryResult(UpdateDeliveryRequest data) async {
    UpdateDeliveryResponse? result = await updateDeliveryRepository
        .updateDelivery(data);
    if (result?.status == true) {
      logger.i('UpdateDeliveyStatus ');
      Get.to(() => HomeView(selectedIndex: 1));
      sendRiderNotification();
    }
  }

  final createDeliveryRepository createDeliveryRepo = createDeliveryRepository();


  Future<void> createDelivery(List<OrderDetails> orders) async {
    String assignTime = DateFormat("yyyy-MM-dd HH:mm:ss").format(DateTime.now());

    List<CreateDelivery> deliveries = orders.map((data) {
      DateTime parsedDate = DateTime.parse(data.deliverydate.toString());
      String formattedDeliveryDate = DateFormat('yyyy-MM-dd HH:mm:ss').format(parsedDate);

      return CreateDelivery(
        assigntime: assignTime,
        applocationid: data.applocationid,
        tenantid: data.tenantid,
        customerid: data.customerid,
        categoryid: data.categoryid,
        configid: data.configid,
        deliveryaddress: data.deliveryaddress,
        deliverycharges: data.deliverycharge?.toDouble(),
        deliverycontactno: data.deliverycontactno,
        deliverycustomer: data.deliverycustomer,
        deliverycustomerid: data.customerid,
        deliverydate: formattedDeliveryDate,
        deliveryid: data.deliveryid,
        deliverylocation: "",
        deliverylocationid: data.deliverylocationid,
        droplat: data.deliverylat,
        droplon: data.deliverylong,
        itemcount: data.itemcount,
        kms: "0.0",
        locationid: data.locationid,
        moduleid: data.moduleid,
        orderamount: 0,
        orderheaderid: data.orderheaderid,
        orderid: data.orderid,
        ordernotes: data.ordernotes,
        orderstatus: "pending",
        partnerid: data.partnerid,
        paymenttype: 42,
        pickupaddress: data.pickupaddress,
        pickupcontactno: data.pickupcontactno,
        pickupcustomer: data.pickupcustomer,
        pickuplat: data.pickuplat,
        pickuplocation: "",
        pickuplocationid: data.pickuplocationid,
        pickuplon: data.pickuplong,
        subcategoryid: data.subcategoryid,
        userid: riderUserIdList,
      );
    }).toList();

    await createDeliveryResult(deliveries);
  }




  Future<void> createDeliveryResult(List<CreateDelivery> deliveries) async {
    for (CreateDelivery data in deliveries) {
      CreateDeliveryResponse? result = await createDeliveryRepo.createDelivery(deliveries);
      if (result?.status == true) {
        logger.i('UpdateDeliveryStatus for delivery ID: ${data.deliveryid}');
      }
    }
    btnNotifyRiderController.reset();
    /// Navigate to HomeView and send notification after processing all deliveries
    Get.to(() => HomeView(selectedIndex: 0));
    sendRiderNotification();
  }


  sendRiderNotification() async {
    sendRiderNotificationResult(
        RiderNotificationRequest(
          notification: NotificationRider(
            title: "NearleXpress",
            image: "",
            body: "Order have been placed for delivery",
            sound: "ring",
          ),
          token: riderFcmToken.join(','),
        )
    );
  }

  final NotificationRepository notificationRepository = NotificationRepository();

  //
  sendRiderNotificationResult(RiderNotificationRequest data)async{
    NotificationResponse? result = await notificationRepository.notifyRider(data);
    if(result?.status == true){
      Toast.showToast('Notified Rider Successfully');
    }
  }

}