import 'dart:convert';
import 'dart:math';

import 'package:sefer_driver/views/widgets/error_snakbar.dart';
import 'package:flutter/material.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:get/get.dart';
import 'package:sefer_driver/constant/box_name.dart';
import 'package:sefer_driver/constant/links.dart';
import 'package:sefer_driver/controller/functions/crud.dart';
import 'package:sefer_driver/controller/functions/secure_storage.dart';
import 'package:sefer_driver/main.dart';
import 'package:sefer_driver/views/auth/verify_email_page.dart';

import '../functions/encrypt_decrypt.dart';

class LoginController extends GetxController {
  final formKey = GlobalKey<FormState>();
  final formKeyAdmin = GlobalKey<FormState>();
  TextEditingController emailController = TextEditingController();
  TextEditingController phoneController = TextEditingController();
  TextEditingController passwordController = TextEditingController();
  TextEditingController adminPasswordController = TextEditingController();
  TextEditingController adminNameController = TextEditingController();
  bool isAgreeTerms = false;
  bool isloading = false;
  final FlutterSecureStorage _storage = const FlutterSecureStorage();

  void changeAgreeTerm() {
    isAgreeTerms = !isAgreeTerms;
    update();
  }

  void saveAgreementTerms() {
    box.write(BoxName.agreeTerms, 'agreed');
    update();
  }

  void saveCountryCode(String countryCode) {
    box.write(BoxName.countryCode, countryCode);
    update();
  }

  void login() async {
    isloading = true;
    update();
    var res = await CRUD().get(link: AppLink.login, payload: {
      'email': emailController.text,
      'phone': phoneController.text,
      'password': passwordController.text
    });
    isloading = false;
    update();
    if (res == 'failure') {
      //Failure
      mySnackeBarError('');
    } else {
      var jsonDecoeded = jsonDecode(res);
      if (jsonDecoeded.isNotEmpty) {
        if (jsonDecoeded['status'] == 'success') {
          if (jsonDecoeded['data'][0]['verified'] == 1) {
            box.write(BoxName.driverID, jsonDecoeded['data'][0]['id']);
            box.write(BoxName.emailDriver, (jsonDecoeded['data'][0]['email']));
            box.write(
                BoxName.nameDriver,
                jsonDecoeded['data'][0]['first_name'] +
                    ' ' +
                    jsonDecoeded['data'][0]['last_name']);
            box.write(BoxName.phone, jsonDecoeded['data'][0]['phone']);
            SecureStorage().saveData(BoxName.password, passwordController.text);
            // Get.offAll(() => const MapPagePassenger());
            isloading = false;
            update();
            await CRUD().post(link: AppLink.addTokens, payload: {
              'token': box.read(BoxName.tokenFCM),
              'passengerID': box.read(BoxName.passengerID).toString()
            });
          } else {
            isloading = false;
            update();
            Get.defaultDialog(
              title: 'You must Verify email !.'.tr,
              middleText: '',
              backgroundColor: Colors.yellow[300],
              onConfirm: () async {
                int randomNumber = Random().nextInt(100000) + 1;
                await CRUD().post(link: AppLink.sendVerifyEmail, payload: {
                  'email': emailController.text,
                  'token': randomNumber.toString(),
                });
                Get.to(() => const VerifyEmailPage());
              },
            );
          }
        } else if (jsonDecoeded['status'] == 'Failure') {
          mySnackeBarError(jsonDecoeded['data']);
          isloading = false;
          update();
        }
      } else {
        isloading = false;
        update();
      }
    }
  }

  goToMapPage() {
    if (box.read(BoxName.email) != null) {
      // Get.offAll(() => const MapPagePassenger());
    }
  }

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