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:ride/constant/box_name.dart';
import 'package:ride/constant/links.dart';
import 'package:ride/controller/functions/crud.dart';
import 'package:ride/controller/functions/secure_storage.dart';
import 'package:ride/main.dart';
import 'package:ride/views/auth/verify_email_page.dart';
import 'package:ride/views/home/map_page.dart';

class LoginController 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.login, payload: {
      'email': emailController.text,
      'phone': phoneController.text,
      'password': passwordController.text
    });
    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.passengerID, jsonDecoeded['data'][0]['id']);
            box.write(BoxName.email, jsonDecoeded['data'][0]['email']);
            box.write(BoxName.name, jsonDecoeded['data'][0]['first_name']);
            box.write(BoxName.phone, jsonDecoeded['data'][0]['phone']);
            SecureStorage().saveData(BoxName.password, passwordController.text);
            Get.offAll(() => MapPage());
            isloading = false;
            update();
            print(box.read(BoxName.passengerID).toString());
            print(box.read(BoxName.tokenFCM));
            await CRUD().post(link: AppLink.addTokens, payload: {
              'token': box.read(BoxName.tokenFCM),
              'passengerID': box.read(BoxName.passengerID).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(() => const VerifyEmailPage());
              },
            );
          }
        } 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();
      }
    }
  }

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

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