import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:service/constant/links.dart';
import 'package:service/controller/functions/crud.dart';

import '../constant/box_name.dart';
import '../main.dart';
import '../print.dart';
import '../views/home/main.dart';

import 'package:flutter_secure_storage/flutter_secure_storage.dart';

import 'functions/initilize.dart';

class LoginController extends GetxController {
  var email = TextEditingController();
  var password = TextEditingController();
  final formKey = GlobalKey<FormState>();

  // Use FlutterSecureStorage instead of GetStorage
  final FlutterSecureStorage storage = const FlutterSecureStorage();

  void login() async {
    String? storedEmail = await storage.read(key: 'email');
    String? storedPassword = await storage.read(key: 'password');

    await CRUD()
        .getJWT(storedPassword ?? password.text, storedEmail ?? email.text);

    if (storedEmail != null) {
      var payload = {
        "email": storedEmail,
        "password": storedPassword,
      };
      Log.print('payload: ${payload}');
      var res = await CRUD().get(link: AppLink.login, payload: payload);
      Log.print('res: ${res}');

      // if (res != 'failure') {
      var d = jsonDecode(res);
      Log.print('d: ${d}');
      if (d['message'] == "Login successful") {
        // Save data securely in FlutterSecureStorage

        await box.write(BoxName.employeename, d['data']['first_name']);
        Get.off(() => Main());
        // }
      }
    } else {
      if (formKey.currentState!.validate()) {
        var payload = {
          "email": storedEmail ?? email.text,
          "password": storedPassword ?? password.text,
        };
        Log.print('payload: ${payload}');
        var res = await CRUD().get(link: AppLink.login, payload: payload);
        Log.print('res: ${res}');

        // if (res != 'failure') {
        var d = jsonDecode(res);
        Log.print('d: ${d}');
        if (d['message'] == "Login successful") {
          // Save data securely in FlutterSecureStorage
          await storage.write(key: 'email', value: d['data']['email']);
          await storage.write(key: 'name', value: d['data']['first_name']);
          await storage.write(key: 'driverID', value: d['data']['id']);
          await storage.write(key: 'password', value: password.text);
          await box.write(BoxName.employeename, d['data']['first_name']);

          Get.off(() => Main());
          // }
        }
      }
    }
  }

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