import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../constant/links.dart';
import '../../views/widgets/elevated_btn.dart';
import '../functions/crud.dart';

class BlinkingController extends GetxController {
  final promoFormKey = GlobalKey<FormState>();

  final promo = TextEditingController();
  bool promoTaken = false;
  void applyPromoCodeToPassenger() async {
    //TAWJIHI
    if (promoFormKey.currentState!.validate()) {
      CRUD().get(link: AppLink.getPassengersPromo, payload: {
        'promo_code': promo.text,
      }).then((value) {
        if (value == 'failure') {
          Get.defaultDialog(
              title: 'Promo End !'.tr,
              confirm: MyElevatedButton(
                title: 'Back',
                onPressed: () {
                  Get.back();
                  Get.back();
                },
              ));
        }
        var decode = jsonDecode(value);

        // if (decode["status"] == "success") {
        //   var firstElement = decode["message"][0];
        //   if (double.parse(box.read(BoxName.passengerWalletTotal)) < 0) {
        //     totalPassenger = totalCostPassenger -
        //         (totalCostPassenger * int.parse(firstElement['amount']) / 100);
        //     update();
        //   } else {
        //     totalPassenger = totalCostPassenger -
        //         (totalCostPassenger * int.parse(firstElement['amount']) / 100);
        //     update();
        //   }

        //   totalDriver = totalDriver -
        //       (totalDriver * int.parse(firstElement['amount']) / 100);
        //   promoTaken = true;
        //   update();
        //   Get.back();
        // }
      });
    }
  }

  // Reactive variable for blinking (on/off)
  var isLightOn = false.obs;

  // To animate the border color
  var borderColor = Colors.black.obs;

  Timer? _blinkingTimer;

  // Method to start blinking for 5 seconds
  void startBlinking() {
    int count = 0;

    _blinkingTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      // Toggle light on/off
      isLightOn.value = !isLightOn.value;
      borderColor.value = isLightOn.value
          ? Colors.yellow
          : Colors.black; // Animate border color

      count++;

      // Stop blinking after 5 seconds
      if (count >= 35) {
        timer.cancel();
        isLightOn.value = false; // Ensure light turns off
        borderColor.value = Colors.black; // Reset the border color
      }
    });
  }

  @override
  void onClose() {
    _blinkingTimer?.cancel();
    super.onClose();
  }
}
