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

import 'package:flutter/material.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:get/get.dart';
import 'package:SEFER/constant/box_name.dart';
import 'package:SEFER/constant/links.dart';
import 'package:SEFER/controller/functions/crud.dart';
import 'package:SEFER/controller/functions/secure_storage.dart';
import 'package:SEFER/main.dart';
import 'package:SEFER/views/auth/captin/verify_email_captain.dart';
import 'package:SEFER/views/home/Captin/home_captain/home_captin.dart';

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

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

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

  void login() async {
    isloading = true;
    update();
    var res = await CRUD().get(link: AppLink.loginCaptin, payload: {
      'email': emailController.text,
      'phone': phoneController.text,
      'password': passwordController.text
    });
    print(res);
    if (res == 'Failure') {
      isloading = false;
      update();
      Get.snackbar('Failure', '', backgroundColor: Colors.red);
    } else {
      var jsonDecoeded = jsonDecode(res);
      // print(jsonDecoeded);
      if (jsonDecoeded.isNotEmpty) {
        if (jsonDecoeded['status'] == 'success') {
          print(jsonDecoeded['data'][0]['verified']);
          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']);
            box.write(BoxName.phoneDriver, jsonDecoeded['data'][0]['phone']);
            SecureStorage()
                .saveData(BoxName.passwordDriver, passwordController.text);
            Get.offAll(() => HomeCaptain());
            isloading = false;
            update();
            print(box.read(BoxName.driverID).toString());
            print(box.read(BoxName.tokenDriver));
            await CRUD().post(link: AppLink.addTokensDriver, payload: {
              'token': box.read(BoxName.tokenDriver),
              'captain_id': box.read(BoxName.driverID).toString()
            }).then((value) => print('cccc'));
          } 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(),
                }).then((value) => print(value));
                Get.to(() => VerifyEmailCaptainPage());
              },
            );
          }
        } else if (jsonDecoeded['status'] == 'Failure') {
          Get.snackbar(jsonDecoeded['status'], jsonDecoeded['data'],
              backgroundColor: Colors.redAccent);
          isloading = false;
          update();
        }
      } else {
        print('res is null');
        isloading = false;
        update();
      }
    }
  }

  void loginByBoxData() async {
    Get.to(() => HomeCaptain());
    await CRUD().post(link: AppLink.addTokensDriver, payload: {
      'token': box.read(BoxName.tokenDriver).toString(),
      'captain_id': box.read(BoxName.driverID).toString()
    });
  }

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

    // if (box.read(BoxName.driverID).toString() != null) {
    //   loginByBoxData();
    // }
  }
}
