import 'package:flutter/material.dart' hide Notification;
import 'package:get/get.dart' hide Response;
import 'package:intl/intl.dart';

import 'package:shared_preferences/shared_preferences.dart';
import '../../Data/Repository/Notification/Notificationrepository.dart';
import '../../Data/Repository/Rider/get_rider_repo.dart';
import '../../Data/Repository/Summary/ordersrepository.dart';
import '../../Data/Repository/Tenants/Tenantsrepository.dart';
import '../../Data/Repository/update_delivery/update_delivery.dart';
import '../../Helper/Constants/Colorconstants.dart';
import '../../Helper/Logger.dart';
import '../../Helper/customDio.dart';
import '../../Helper/toast.dart';
import '../../Model/Request/Notification/Notification_request_rider.dart';
import '../../Model/Request/Notification/Notificationrequest.dart';
import '../../Model/Request/update_delivery/update_delivery.dart';
import '../../Model/Response/Notification/Notificationresponse.dart';
import '../../Model/Response/Riders/get_rider_model.dart';
import '../../Model/Response/Summary/Getsummarysresponse.dart';
import '../../Model/Response/Tenants/Tenantinforesponse.dart';
import '../../Model/Response/update_delivery_response/update_delivery_response.dart';
import '../../View/Home/Homeview.dart';

class DashboardController extends GetxController with SingleGetTickerProviderMixin{

  String? userName;
  String? businessName;
  String? businessLocation;
  String? adminToken;
  String? currentTime;
  String? notificationDate;
  TenantDetails? tenantInfo;
  int tenantId = 0;
  int moduleId = 0;
  int locationId = 0;
  int tabIndex = 0;
  int? approved;

  var orderId;
  var orderHeaderId;
  var userId;

  DateTime? now;

  late TabController tabController;

  OrderSummaryRepository orderSummaryRepository = OrderSummaryRepository();
  TenantRepository tenantRepository = TenantRepository();

  List <GetRiderDetails> riderDetails = [];
  RidersRepository ridersRepository = RidersRepository();


  final List<Tab> tabs = <Tab>[
    Tab(
    text: "Placed",
    icon: Icon(Icons.access_time_filled_outlined,color: ColorConstants.primaryColor,size: 25,),
  ),
    Tab(
    text: "OnGoing",
    icon: Icon(Icons.rotate_right,color: ColorConstants.primaryColor,size: 25,),
  ),
    Tab(
    text: "Cancelled",
    icon: Icon(Icons.cancel,color: ColorConstants.primaryColor,size: 25,),
  ),
    Tab(
      text: "Completed",
      icon: Icon(Icons.check_circle,color: ColorConstants.primaryColor,size: 25,),
    ),


  ];

  getDetails() async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
      // userName = prefs.getString('userName')??'';
      businessName = prefs.getString('tenantName')??'';
      businessLocation = prefs.getString('locationName')??'';
      logger.i('Business Name prefs: ${businessName}');
      logger.i('Business Locations prefs: ${businessLocation}');
      update();
  }

  getTenantInfo() async{
    TenantInfo? result = await tenantRepository.getTenantInfo();
    tenantInfo = result?.details;
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString('tenantName', tenantInfo?.tenantname ?? '');
    prefs.setString('locationName', tenantInfo?.applocation ?? '');
    prefs.setInt('tenantId', tenantInfo?.tenantid ?? 0);
    prefs.setInt('categoryId', tenantInfo?.categoryid ?? 0);
    prefs.setInt('locationId', result?.details?.locationid ?? 0);
    logger.i('Business Locations : ${businessLocation}');
    approved =  result?.details?.approved;
    update();
  }



  getOrders()async{

  }


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

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


  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(DeliveriesDetails 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){
      Get.to(()=>HomeView(selectedIndex: 1));
      // 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');
    }
  }



  @override
  void onInit() {
    tabController = TabController(vsync: this, length: tabs.length);
    // TODO: implement onInit
    super.onInit();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      getDetails(); // Runs after first frame is rendered
    });
    logger.i('controller Init state called : ');
    //getTenantInfo();
  }
}