import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:SEFER/constant/links.dart';
import 'package:SEFER/constant/style.dart';
import 'package:SEFER/main.dart';
import 'package:SEFER/views/widgets/elevated_btn.dart';

import '../../../constant/box_name.dart';
import '../../../constant/table_names.dart';
import '../../functions/crud.dart';
import '../../functions/location_controller.dart';
import 'home_captain_controller.dart';

class OrderRequestController extends GetxController {
  double progress = 0;
  double progressSpeed = 0;
  int duration = 11;
  int durationSpeed = 20;
  int remainingTime = 0;
  int remainingTimeSpeed = 0;
  String countRefuse = '0';
  bool applied = false;
  final locationController = Get.put(LocationController());

  @override
  void onInit() {
    getRefusedOrderByCaptain();
    // calculateConsumptionFuel();
    update();
    super.onInit();
  }

  void changeApplied() {
    applied = true;
    update();
  }

  double mpg = 0;
  calculateConsumptionFuel() {
    mpg = Get.find<HomeCaptainController>().fuelPrice /
        12; //todo in register car add mpg in box
  }

  void getRefusedOrderByCaptain() async {
    DateTime today = DateTime.now();
    int todayDay = today.day;

    String driverId = box.read(BoxName.driverID).toString();

    String customQuery = '''
    SELECT  COUNT(*) AS count
    FROM ${TableName.driverOrdersRefuse}
    WHERE driver_id = '$driverId'
   AND created_at LIKE '%$todayDay%'
  ''';

    try {
      List<Map<String, dynamic>> results =
          await sql.getCustomQuery(customQuery);
      countRefuse = results[0]['count'].toString();
      update();
      if (int.parse(countRefuse) > 3) {
        locationController.stopLocationUpdates();
        Get.defaultDialog(
            // backgroundColor: CupertinoColors.destructiveRed,
            barrierDismissible: false,
            title: 'You Are Stopped For this Day !'.tr,
            content: Text(
              'You Refused 3 Rides this Day that is the reason \nSee you Tomorrow!'
                  .tr,
              style: AppStyle.title,
            ),
            confirm: MyElevatedButton(
                title: 'Ok , See you Tomorrow'.tr,
                onPressed: () => Get.back()));
      }
    } catch (e) {
      print('Error executing custom query: $e');
    }
  }

  void startTimer(String driverID, orderID) async {
    for (int i = 0; i <= duration; i++) {
      await Future.delayed(const Duration(seconds: 1));
      progress = i / duration;
      remainingTime = duration - i;

      update();
    }
    if (remainingTime == 0) {
      if (applied == false) {
        print('applied=========================');
        print(applied);
        refuseOrder(orderID);
      }
    }
  }

  void startTimerSpeed(String driverID, orderID) async {
    for (int i = 0; i <= durationSpeed; i++) {
      await Future.delayed(const Duration(seconds: 1));
      progressSpeed = i / durationSpeed;
      remainingTimeSpeed = durationSpeed - i;

      update();
    }
    // if (remainingTimeSpeed == 0) {
    // if (applied == false) {
    //   print('applied=========================');
    //   print(applied);
    //   Get.back();
    //   // refuseOrder(box.read(BoxName.driverID), orderID);
    // }
    // }
  }

  void refuseOrder(
    orderID,
  ) async {
    await CRUD().postFromDialogue(link: AppLink.addDriverOrder, payload: {
      //TODO need review
      'driver_id': box.read(BoxName.driverID),
      // box.read(BoxName.driverID).toString(),
      'order_id': orderID,
      'status': 'Refused'
    });
    await CRUD().post(link: AppLink.updateRides, payload: {
      'id': orderID,
      'rideTimeStart': DateTime.now().toString(),
      'status': 'Refused',
      'driver_id': box.read(BoxName.driverID),
    });

    // applied = true;
    sql.insertData({
      'order_id': orderID,
      'created_at': DateTime.now().toString(),
      'driver_id': box.read(BoxName.driverID).toString(),
    }, TableName.driverOrdersRefuse);
    getRefusedOrderByCaptain();
    box.write(BoxName.statusDriverLocation, 'off');
    update();
    Get.back();
    // Get.offAll(HomeCaptain());
  }

  addRideToNotificationDriverString(
    orderID,
    String startLocation,
    String endLocation,
    String date,
    String time,
    String price,
    String passengerId,
    String status,
    String carType,
    String passengerRate,
    String priceForPassenger,
    String distance,
    String duration,
  ) async {
    await CRUD().post(link: AppLink.addWaitingRide, payload: {
      'id': orderID,
      'start_location': startLocation,
      'end_location': endLocation,
      'date': date,
      'time': time,
      'price': price,
      'passenger_id': passengerId,
      'status': status,
      'carType': carType,
      'passengerRate': passengerRate,
      'price_for_passenger': priceForPassenger,
      'distance': distance,
      'duration': duration,
    });
  }
}
