import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:qpay/abstracts/AbstractController.dart';
import 'package:qpay/http/http.dart';
import 'package:qpay/models/api_response.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../onboarding_controller.dart';

class PhoneModel {
  bool isLoading = false;
  String? errorMessage;
  String? status = 'failed';
}

class PhoneController extends AbstractController {
  PhoneModel model = PhoneModel();
  @override
  BuildContext context;

  late OnboardingController onboardingController;
  late SharedPreferences prefs;

  final Http http = Http();

  PhoneController(this.context) {
    onboardingController = Provider.of<OnboardingController>(
      context,
      listen: false,
    );
  }

  void updatePhone(String phone) {
    onboardingController.updatePhone(phone);
    notifyListeners();
  }

  Future<ApiResponse<Map<String, dynamic>>> register() async {
    prefs = await SharedPreferences.getInstance();

    Map user = {
      "username": onboardingController.model.email,
      "email": onboardingController.model.email,
      "firstName": onboardingController.model.firstName,
      "lastName": onboardingController.model.lastName,
      "password": onboardingController.model.password,
      "phone": onboardingController.model.phone,
      "tempUid": prefs.get("userId"),
    };

    try {
      model.isLoading = true;
      notifyListeners();

      Map response = await http.post(
        '/auth/register',
        user,
      );
      model.status = response['state'];
      if (response['state'] == 'failed') {
        model.errorMessage = response['message'];
        showErrorSnackBar(model.errorMessage);
        model.isLoading = false;
        notifyListeners();
        return ApiResponse.failure(response['message'] ?? "Registration failed");
      }
      Map body = response['body'];
      body['workflowId'] = response['workflowId'];
      onboardingController.updateModel(body);

      model.isLoading = false;
      notifyListeners();
      return ApiResponse.success(Map<String, dynamic>.from(body));
    } catch (e) {
      logger.e(e);
      showErrorSnackBar(
        "Problem during registration, please try again or contact support?",
      );
      model.isLoading = false;
      notifyListeners();
      return ApiResponse.failure(
        "Problem during registration, please try again or contact support?",
      );
    }
  }
}
