import 'dart:convert';
import 'dart:io';
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/verify_email_page.dart';
import 'package:SEFER/views/home/map_page_passenger.dart';

import '../../views/admin/admin_home_page.dart';
import '../functions/device_info.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;
    print(isAgreeTerms);
    update();
  }

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

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

  void adminDashboardOpen() async {
    if (formKeyAdmin.currentState!.validate()) {
      await DeviceInfoPlus.getDeviceInfo();
      if (Platform.isAndroid) {
        // print(DeviceInfoPlus.deviceDataList['serialNumber']);
        // var res = await CRUD().get(link: AppLink.getAdminUser, payload: {
        //   // 'device_number': DeviceInfoPlus.deviceData['serialNumber'].toString(),
        // });
        // var d = jsonDecode(res);
        // // print(d);
        // // if (DeviceInfoPlus.deviceData['serialNumber'] ==
        // d['message']['device_number']) {
        Get.back();
        Get.to(() => const AdminHomePage());
        // }
      }
      if (Platform.isIOS) {
        // print(DeviceInfoPlus.deviceData['identifierForVendor']);
        // var res = await CRUD().get(link: AppLink.getAdminUser, payload: {
        //   'device_number': DeviceInfoPlus.deviceData['identifierForVendor'].toString(),
        // });
        // var d = jsonDecode(res);
        // print(d);
        // if (DeviceInfoPlus.deviceData['serialNumber'] ==
        // d['message']['device_number']) {
        Get.back();
        Get.to(() => const AdminHomePage());
        // }
      }
    }
  }

  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') {
      Get.snackbar('Failure', '', backgroundColor: Colors.red);
    } else {
      // print(res);
      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'] +
                    ' ' +
                    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();
            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 MapPagePassenger());
    }
  }

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