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

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

class OrderRequestController extends GetxController {
  double progress = 0;
  int duration = 25;
  int remainingTime = 0;
  String countRefuse = '0';
  bool applied = false;

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

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

  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) {
        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(driverID, orderID);
      }
    }
  }

  void refuseOrder(String driverID, orderID) async {
    await CRUD().postFromDialogue(link: AppLink.addDriverOrder, payload: {
      'driver_id': box.read(BoxName.driverID).toString(),
      // box.read(BoxName.driverID).toString(),
      'order_id': orderID,
      'status': 'Refused'
    });
    Get.back();
    sql.insertData({
      'order_id': orderID,
      'created_at': DateTime.now().toString(),
      'driver_id': box.read(BoxName.driverID).toString(),
    }, TableName.driverOrdersRefuse);
    getRefusedOrderByCaptain();
    update();
  }
}
