// ignore_for_file: use_build_context_synchronously

import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:provider/provider.dart';
import 'package:sapaly_shop/constants/global_variables.dart';
import 'package:sapaly_shop/constants/utils.dart';
import 'package:sapaly_shop/features/screens/home/home_screen.dart';
import 'package:sapaly_shop/models/auth/login/login_request_model.dart';
import 'package:sapaly_shop/models/auth/login/login_response_model.dart';
import 'package:sapaly_shop/models/auth/register/register_request_model.dart';
import 'package:sapaly_shop/models/auth/register/register_response_model.dart';
import 'package:sapaly_shop/providers/user_provider.dart';
import 'package:sapaly_shop/themes/app_theme.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../constants/error_handling.dart';

class AuthService {
  Future<void> login({
    required LoginRequestModel loginRequestModel,
    required BuildContext context,
  }) async {
    try {
      var response = await http.post(Uri.parse('$kBaseUrl/jwt/login'),
          body: loginRequestModel.toMap(),
          headers: {
            'Accept': 'application/json',
          });

      if (response.statusCode == HttpStatus.ok) {
        var data = response.body;
        var loginResponse = LoginResponseModel.fromJson(data);
        debugPrint('LOGIN  ${loginResponse.user.email}');
      }

      httpErrorHandle(
        response: response,
        context: context,
        onSuccess: () async {
          SharedPreferences prefs = await SharedPreferences.getInstance();
          Provider.of<UserProvider>(context, listen: false)
              .setUser(response.body);
          await prefs.setString(
              'token', jsonDecode(response.body)['data']['token']);
          Navigator.of(context).pushNamedAndRemoveUntil(
            HomeScreen.routeName,
            (route) => false,
          );
          showSnackBar(
            context,
            content: 'login_success',
            backgroundColor: AppTheme.lightPrimaryColor,
            textColor: AppTheme.whiteColor,
          );
        },
      );
    } catch (e) {
      showSnackBar(
        context,
        content: e.toString(),
        backgroundColor: AppTheme.redColor,
        textColor: AppTheme.whiteColor,
      );
      debugPrint('Login ERROR ${e.toString()}');
    }
  }

  // Register
  Future<void> register({
    required RegisterRequestModel registerRequestModel,
    required BuildContext context,
  }) async {
    try {
      var response = await http.post(
        Uri.parse('$kBaseUrl/jwt/register'),
        body: registerRequestModel.toJson(),
        headers: {'Accept': 'application/json'},
      );

      if (response.statusCode == HttpStatus.ok) {
        var data = response.body;
        var registerResponse = registerResponseModelFromJson(data);
        debugPrint('REGISTER ${registerResponse.user.email}');
      }
      httpErrorHandle(
        response: response,
        context: context,
        onSuccess: () async {
          SharedPreferences prefs = await SharedPreferences.getInstance();
          Provider.of<UserProvider>(context, listen: false)
              .setUser(response.body);
          await prefs.setString(
              'token', jsonDecode(response.body)['data']['token']);
          Navigator.of(context).pushNamedAndRemoveUntil(
            HomeScreen.routeName,
            (route) => false,
          );
          showSnackBar(
            context,
            content: 'signup_success',
            backgroundColor: AppTheme.lightPrimaryColor,
            textColor: AppTheme.whiteColor,
          );
        },
      );
    } catch (e) {
      showSnackBar(
        context,
        content: e.toString(),
        backgroundColor: AppTheme.redColor,
        textColor: AppTheme.whiteColor,
      );
      debugPrint('Register ERROr ${e.toString()}');
    }
  }

  // get user data
  Future<void> getUserData({
    required BuildContext context,
  }) async {
    try {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      String? token = prefs.getString('token');
      if (token == null) {
        prefs.setString('token', '');
      }

      // await http.post(Uri.parse('$uri'));
    } catch (e) {}
  }
}
