import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../app.dart';

class LoginController extends GetxController {
  final ProfileController _profileController = Get.put(ProfileController());

  final formKey = GlobalKey<FormState>();

  TextEditingController phoneCtrl = new TextEditingController();
  TextEditingController passwordCtrl = new TextEditingController();

  RxBool isLoading = false.obs;

  @override
  void dispose() {
    phoneCtrl.dispose();
    passwordCtrl.dispose();
    super.dispose();
  }

  Future<void> login() async {
    debugPrint('on login tapped');

    if (formKey.currentState!.validate()) {
      isLoading.value = true;
      update();

      final maskedPhoneNumber = phoneCtrl.value.text;
      final phone = maskedPhoneNumber.replaceAll(RegExp(r'\D+'), '');

      final Map<String, dynamic> params = {
        'phone': phone,
        'password': passwordCtrl.text.trim(),
        'device_name': await getDeviceName(),
      };

      final result = await AuthApi.login(params);

      isLoading.value = false;
      update();

      if (result) {
        setLoginStatus(true);
        _profileController.onInit();
      }
    }
  }

  Future<void> getOtp() async {}
}
