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 'package:service/controller/functions/device_helper.dart';
import 'package:service/controller/functions/encrypt_decrypt.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';

class LoginController extends GetxController {
  var email = TextEditingController(); // Kept for UI compatibility
  var password = TextEditingController();
  final formKey = GlobalKey<FormState>();

  final FlutterSecureStorage storage = const FlutterSecureStorage();

  void login() async {
    // Ensure fingerprint is ready
    String fingerprint = box.read(BoxName.fingerPrint) ?? '';
    if (fingerprint.isEmpty) {
      fingerprint = await DeviceHelper.getDeviceFingerprint();
    }

    String? storedPassword = await storage.read(key: 'password');
    String pass = storedPassword ?? password.text;

    if (pass.isEmpty && !formKey.currentState!.validate()) return;

    var payload = {
      "fingerprint": fingerprint,
      "password": pass,
      "aud": "service",
    };

    Log.print('🚀 Login Payload: $payload');
    var res = await CRUD().post(link: AppLink.login, payload: payload);
    Log.print('📥 Login Response: $res');

    if (res != 'failure' && res is Map && res['status'] == 'success') {
      var d = res['message']; // V1 returns {status, message: {jwt, data: {user...}}}
      
      // Store JWT
      final jwt = d['jwt'];
      box.write(BoxName.jwt, c(jwt));

      // Store User Data
      var userData = d['data'];
      await storage.write(key: 'name', value: userData['first_name']);
      await storage.write(key: 'driverID', value: userData['id'].toString());
      await storage.write(key: 'password', value: pass);
      await box.write(BoxName.employeename, userData['first_name']);
      await box.write(BoxName.password, pass);

      Get.offAll(() => Main());
    } else {
      Get.snackbar(
        'خطأ'.tr,
        res is Map ? res['message'].toString().tr : 'فشل تسجيل الدخول'.tr,
        backgroundColor: Colors.red.withOpacity(0.7),
        colorText: Colors.white,
      );
    }
  }

  @override
  void onInit() async {
    await EncryptionHelper.initialize();
    await DeviceHelper.getDeviceFingerprint();
    
    // Auto login if credentials exist
    String? storedPassword = await storage.read(key: 'password');
    if (storedPassword != null) {
      login();
    }


    super.onInit();
  }
}
